ng2-validation icon indicating copy to clipboard operation
ng2-validation copied to clipboard

minDate value dependent on another FormControl.. Model Driven

Open KshitizGIT opened this issue 7 years ago • 2 comments

I would like to validate end date should be always greater than starting date. I tried to use the minDate validation. But the minDate value is being changed at runtime when the starting date is changed.

Any way, I can achieve this using this library ??

KshitizGIT avatar Apr 18 '17 11:04 KshitizGIT

I need the same here! Did you or someone else achieved that?

lucasmafra avatar May 01 '17 14:05 lucasmafra

I just found a solution, it may work for you:

First of all, I have in my template two date inputs (let's call them startDate and endDate). The second one is binded to a formControl called "endDateControl", which has no validators yet.

Then, I set an event that handles any change in my startDate. In my handler function, I can set the validators for my endDate, calling endDateControl.setValidators(value) and passing my minDate as parameter. Putting all together, we have something like this:

EXAMPLE.HTML

<input type="date" #startDate (change)="handleNewStartDate(startDate)"> <input type="date" #endDate [formControl]="endDateFormControl">

EXAMPLE.TS

/*in the beginning of the class we declare our form control with an empty array of validators*/ endDateFormControl = newFormControl('', [])

Then, in my handlerChange function: handleNewStartDate(value: any) { this.endDateFormControl.setValidators([CustomValidators.minDate(value.date)] }

Hope this work!

lucasmafra avatar May 01 '17 14:05 lucasmafra