预期验证器返回 Promise 或 Observable [英] Expected validator to return Promise or Observable
问题描述
我正在尝试对 Angular 5 进行自定义验证,但遇到以下错误
I'm trying to do a custom validation on Angular 5 but I'm facing the following error
Expected validator to return Promise or Observable
如果值与所需的值不匹配,我只想向表单返回一个错误,这是我的代码:
I just want to return an error to the form if the value doesn't match the required, here's my code:
这是我的表单所在的组件
This is the component where my form is
constructor(fb: FormBuilder, private cadastroService:CadastroService) {
this.signUp = fb.group({
"name": ["", Validators.compose([Validators.required, Validators.minLength(2)])],
"email": ["", Validators.compose([Validators.required, Validators.email])],
"phone": ["", Validators.compose([Validators.required, Validators.minLength(5)])],
"cpf": ["", Validators.required, ValidateCpf]
})
}
此代码在带有我要实施的验证的文件中:
This code is in the file with the validation I want to implement:
import { AbstractControl } from '@angular/forms';
export function ValidateCpf(control: AbstractControl){
if (control.value == 13445) {
return {errorCpf: true}
}
return null;
}
这种类型的验证是否只适用于 observables 或者我可以在没有承诺或 observable 的情况下进行?
Does that type of validation only work with observables or can I do it without being a promise or observable?
推荐答案
这意味着你必须在数组中添加多个验证器
.示例:
有错误
profileFormGroup = {
budget: [null, Validators.required, Validators.min(1)]
};
以上一个抛出错误,验证器返回 Promise 或 Observable
修正:
profileFormGroup = {
budget: [null, [Validators.required, Validators.min(1)]]
};
说明:
在 Angular Reactive 表单验证中,使用内置验证器完成,当使用多个验证器时,可以在第二个位置以数组形式给出.
In angular Reactive form validation done by using in-built validators which could given in array in 2nd postion, when multiple validators used.
FIELD_KEY:[INITIAL_VALUE,[LIST_OF_VALIDATORS]]
FIELD_KEY: [INITIAL_VALUE, [LIST_OF_VALIDATORS]]
这篇关于预期验证器返回 Promise 或 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!