Sun
Sun

Reputation: 4718

Create a custom validator to validate against multiple form fields

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

Upvotes: 0

Views: 1256

Answers (1)

Saloo
Saloo

Reputation: 816

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');
    ....
    }

Upvotes: 1

Related Questions