ng2-validation
ng2-validation copied to clipboard
minDate value dependent on another FormControl.. Model Driven
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 ??
I need the same here! Did you or someone else achieved that?
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!