I need to implement async validation dependent on multiple form fields, so I placed the validation on FormGroup
. But the validation function is not getting called. Surely am missing something.
heroForm: FormGroup;
ngOnInit(): void {
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i)
]),
'alterEgo': new FormControl(this.hero.alterEgo, {
updateOn: 'blur'
}),
'power': new FormControl(this.hero.power, Validators.required)
}, null,this.validate.bind(this));
}
validate(
ctrl: FormGroup
): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
console.log(ctrl)
return this.heroesService.isAlterEgoTaken(ctrl.controls.alterEgo.value).pipe(
map(isTaken => {
console.log(isTaken);
return (isTaken ? { uniqueAlterEgo: true } : null)
}),
catchError(() => null)
);
}
Created a demo here: https://stackblitz.com/edit/angular-xtqhqi
Async validators are fired only when all sync validators return null. So remove all form errors and then the async validator will be called.
Don't forget that you have updateOn: 'blur'
specified for that input, so you have to blur the input to trigger validation.