gpt4 book ai didi

angular - angular2 中的直接自定义验证

转载 作者:太空狗 更新时间:2023-10-29 17:41:53 26 4
gpt4 key购买 nike

我已经创建了这个验证函数:

private customValidateField(c: FormControl): any {
return c.value[0] === 'a' ? null : { notValid: true };
}

所以,在我的 react 形式上:

constructor(private fb: FormBuilder)
{
this.form = this.fb.group({
field: ['', Validators.required, this.customValidateField],
...
}
}

当我在这个字段中写入任何字符时,我得到这个错误:

Error: Expected validator to return Promise or Observable.

有什么想法吗?

最佳答案

“字段”数组中的第三项是异步验证器(或它们的数组)。所以要指定多个同步验证器,你需要:

将它们作为数组传递

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

关于angular - angular2 中的直接自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com