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?

Sammy
  • 3,395
  • 7
  • 49
  • 95

1 Answers1

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • +1 :). I think the [**docs**](https://angular.io/api/forms/FormBuilder#overview) 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`). – developer033 Jun 20 '17 at 05:59