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?
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