Search code examples
angulartypescriptangular-reactive-formsangular11angular-validation

Angular 11 Reactive form validation: Start date is less than End date


I am using reactive form and trying to use cross field validation for start and End dates. Start date should be less that end date. Also user should not be able to select date greater than today date. Note: I am not using matdatepicker. Following is my implementation:

export const dateValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const start = control.get('dateStart');
const end = control.get('dateEnd');
console.log("validators called");  
return start !== null && end !== null && start < end 
? null :{ dateValid:true };

};

HTML

<p *ngIf="myForm.errors?.dateValid && (myForm.touched ||myForm.dirty)">Please add a valid from and to date</p>

myform.ts

 constructor(private fb:FormBuilder) {
   this.myForm = new FormGroup({
      dateStart: new FormControl('', Validators.required),
      dateEnd: new FormControl('', Validators.required)
    },{validators:dateValidator});
}

Can anyone help me figure what is wrong with the code?


Solution

  • You need to check control.value, not the control itself.

    export const dateValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
    const start = control.get('dateStart');
    const end = control.get('dateEnd');
    console.log("validators called");  
    return start.value !== null && end.value !== null && start.value < end.value 
    ? null :{ dateValid:true };
      }