In an Angular 4 application, how can I validate two fields of a form doing a comparison?
For example, let's suppose that my form has a startDate and an endDate date fields and I want to make sure that the endDate must be bigger than the startDate.
When you want to implement validations containing one or more sibling (form)controls, you have to define the validator function on a level up/above that of the sibling controls. For ex:
Then outside the component class's definition (in the same file), define the function
checkIfEndDateAfterStartDateas well.This validation will make the
FormGroupinvalid by adding the error-flag (hereinvalidEndDate) totrueto the errors object for thatFormGroup. If you want to have specific errors to be set on any of the sibling controls instead, then you can manually set the error flags on thatformControlby using something like,c.get('endDate').setErrors({ invalidEndDate: true }). If you do this, then make sure you clear them for a valid case by setting the errors tonulllike this,c.get('endDate').setErrors(null).A live demo of a similar validation can be seen here.