I've created this validation function:
private customValidateField(c: FormControl): any {
return c.value[0] === 'a' ? null : { notValid: true };
}
So, on my reactive form:
constructor(private fb: FormBuilder)
{
this.form = this.fb.group({
field: ['', Validators.required, this.customValidateField],
...
}
}
When I'm writing any character into this field I'm getting this error:
Error: Expected validator to return Promise or Observable.
Any ideas?
The third item in the "field" array is an asynchronous validator (or an array of them). So to specify multiple synchronous validators, you need to:
Pass them as an array
this.fb.group({
'formControlName': [this.hero.name, [
Validators.required,
Validators.minLength(4)
]]
});
or combine them (as Jordi wrote) using
Validators.compose(...)
FormBuilder API doc doesn't discuss the parameters in detail, but since it's just a shortcut for creating FormGroup with FormControl-s, you can take a look at the FormControl constructor: https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html
I've just used Validators.compose
:
this.form = this.fb.group({
field: ['', Validators.compose([Validators.required, this.validateCardNumber])],
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With