0

I'm building my FormGroup in the following manner:

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, (fg: FormGroup) => {
  console.log('validate');
  return moment.unix(fg.value.departureDate.epoc).diff(moment.unix(fg.value.arrivalDate.epoc)) > 0 ?
    null : {
      'departureBeforeArrival': true
    };
});
this.formGroup = this.fb.group({
  dates: this.datesGroup,
  accommodation: ['', Validators.required]
});

But the validation arrow function above is never triggered; the console never logs. What am I doing wrong?

1 Answer 1

1

FormBuilder.group method takes 2 parameters:

group(controlsConfig: {
        [key: string]: any;
    }, extra?: {
        [key: string]: any;
    } | null): FormGroup;

where extra can be object with property validator and/or asyncValidator.

So i would change your code to this:

this.datesGroup = this.fb.group({
  arrivalDate: [null, Validators.required],
  departureDate: [null, Validators.required]
}, {
  validator: (fg: FormGroup) => {
    console.log('validate');
    return 1 > 0 ?
      null : {
        'departureBeforeArrival': true
      };
  }
});

Live example could be found here https://plnkr.co/edit/BcExweMVcVxy1yKhwmJp?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

+1 :). I think the docs could be better explaining what this "extra" means, as it does for FormControl and FormArray. (I know it's explained well in FormGroup, but it should be also in FormBuilder).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.