繁体   English   中英

使用我自己的验证器时出错(Angular、Reactive-Forms)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM