0

I have the following form setup:

this.form = new FormGroup({
  ...
  year: new FormControl("", validateDateMethod(year, month, day)),
  month: new FormControl("", validateDateMethod(year, month, day)),
  day: new FormControl("", validateDateMethod(year, month, day))
});

I want to create a custom validator to validate the date based on the 3 fields.

Is it possible to create a validator based on multiple form values?

Normal customs validators just take in the current control and any parameter values.

Thanks

Sun
  • 4,458
  • 14
  • 66
  • 108
  • Please look into code in this link: https://stackoverflow.com/a/44449802/3875919 – user3875919 Nov 12 '19 at 09:34
  • I've tried something similar to that but I receive an error: Argument of type is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'. Object literal may only specify known properties, and 'validator' does not exist in type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions – Sun Nov 12 '19 at 09:45
  • I need to use form builder to clear the error – Sun Nov 12 '19 at 09:54
  • You could achieve by setting the custom property in the errors object of the `FormControl` and then display the error message in the DOM using `*ngIf` directive. – user3875919 Nov 12 '19 at 10:17

1 Answers1

1

You can group all the three dates to a formgroup and add validator to it. Then you can validate across all the three fields.

 this.form = new FormGroup({
      ...
      dateGroup:this.formBuilder.group({
      year: new FormControl(""),
      month: new FormControl(""),
      day: new FormControl("")
    },{validator:validateDates}) 
  });

    validateDates(c:AbstractControl){
    const year = c.get('year');
    const month = c.get('month');
    const day = c.get('day');
    ....
    }
user3875919
  • 303
  • 1
  • 2
  • 13
Saloo
  • 816
  • 6
  • 13