我已经创建了这个验证功能:
private customValidateField(c: FormControl): any { return c.value[0] === 'a' ? null : { notValid: true }; }
所以,在我的反应形式上:
constructor(private fb: FormBuilder) { this.form = this.fb.group({ field: ['',Validators.required,this.customValidateField],... } }
当我在这个字段中写任何字符时,我收到此错误:
Error: Expected validator to return Promise or Observable.
有任何想法吗?
解决方法
“field”数组中的第三项是异步验证器(或它们的数组).因此,要指定多个同步验证器,您需要:
将它们作为数组传递
this.fb.group({ 'formControlName': [this.hero.name,[ Validators.required,Validators.minLength(4) ]] });
或者将它们组合起来(如Jordi所写)使用
Validators.compose(...)
FormBuilder API文档没有详细讨论参数,但由于它只是使用FormControl-s创建FormGroup的快捷方式,因此您可以查看FormControl构造函数:
https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html