[英]Angular 6 Reactive Forms Custom Validator Error Displayed from it's OWN data
[英]Error when using my own validator (Angular, Reactive-Forms)
這是我的一段代碼,當我嘗試使用自己的驗證器時,要確保名稱不包含數字:
ngOnInit() {
// HERE
this.bewerberForm = new FormGroup({
'name': new FormControl(null, Validators.required, this.containsNumbers),
'email': new FormControl(null, [Validators.required, Validators.email]),
...
}
containsNumbers(control: FormControl): Promise<any> | Observable<any> {
const promise = new Promise<any>((resolve, reject) => {
for (let i = 0; i < control.value.length; i++) {
if (control.value.charAt(i).match('[0-9]')) {
resolve({ 'nameIsForbidden': true });
break;
} else {
resolve(null);
}
}
});
return promise;
}
我收到以下錯誤,我不明白,因為我已經在另一個項目中這樣做了:
No overload matches this call.
Overload 1 of 5, '(value: FormControlState<null> | null, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<...>', gave the following error.
Type '(control: AbstractControl<any, any>) => ValidationErrors | null' has no properties in common with type 'FormControlOptions'.
Overload 2 of 5, '(value: FormControlState<null> | null, validatorOrOpts?: FormControlOptions | ValidatorFn | ValidatorFn[] | null | undefined, asyncValidator?: AsyncValidatorFn | ... 2 more ... | undefined): FormControl<...>', gave the following error.
Argument of type '(control: FormControl<any>) => Promise<any> | Observable<any>' is not assignable to parameter of type 'AsyncValidatorFn | AsyncValidatorFn[] | null | undefined'.
Type '(control: FormControl<any>) => Promise<any> | Observable<any>' is not assignable to type 'AsyncValidatorFn'.
Types of parameters 'control' and 'control' are incompatible.
Type 'AbstractControl<any, any>' is missing the following properties from type 'FormControl<any>': defaultValue, registerOnChange, registerOnDisabledChangets(2769)
'name': new FormControl(null, Validators.required, this.containsNumbers),
應該
'name': new FormControl(null, [Validators.required, this.containsNumbers]),
驗證器在數組中傳遞,就像您在 email 控件中所做的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.