【问题标题】:Error while adding validator to reactive form将验证器添加到反应式表单时出错
【发布时间】:2017-08-07 09:06:36
【问题描述】:

我创建了一个简单的表单,我想在其中添加一个验证器:

 form;

  constructor() { 
    this.form = new FormGroup({
    'old-password' : new FormControl('', [Validators.required, Validators.minLength(4)], PasswordValidators.checkPassword),
    'new-password' : new FormControl('', [Validators.required, Validators.minLength(4)]),
    'confirm-password' : new FormControl('', [Validators.required, Validators.minLength(4)])
  }, {
      validator: PasswordValidators.passwordsShouldMatch
    });
  }

但在validator 部分我收到一条错误消息:

[ts]
Argument of type '{ validator: (control: AbstractControl) => { passwordsShouldMatch: boolean; }; }' is not assignable to parameter of type 'ValidatorFn'.
  Object literal may only specify known properties, and 'validator' does not exist in type 'ValidatorFn'.
(property) validator: (control: AbstractControl) => {
    passwordsShouldMatch: boolean;
}

当我将表单的构造更改为 FormBuilder 时,它开始工作 - 这是为什么呢?

【问题讨论】:

  • 您是否尝试通过提及您的自定义 validator 来删除 validator:
  • 可以发PasswordValidators.passwordsShouldMatch方法吗?

标签: angular validation typescript


【解决方案1】:

根据api documentation and example,构造函数只是获取验证器函数,而不是像FormBuilder 那样的对象。

所以这应该有效:

constructor() { 
  this.form = new FormGroup({
    'old-password' : new FormControl('', [Validators.required, Validators.minLength(4)], PasswordValidators.checkPassword),
    'new-password' : new FormControl('', [Validators.required, Validators.minLength(4)]),
    'confirm-password' : new FormControl('', [Validators.required, Validators.minLength(4)])
  },
  PasswordValidators.passwordsShouldMatch
  );
}

【讨论】:

    【解决方案2】:

    我不确定您使用的 PasswordValidators 对象是什么样的,但我重新排列了您的代码,为您提供了一个正确语法示例,您应该使用这些语法来实现您想要的:

    export class ModelDrivenForm {
      public form: FormGroup;
    
      constructor() {
        this.form = new FormGroup({
            oldpassword: new FormControl('', [Validators.required, Validators.minLength(4), this.checkPassword]),
            newpassword: new FormControl('', [Validators.required, Validators.minLength(4)]),
            confirmpassword: new FormControl('', [Validators.required, Validators.minLength(4)])
          },
          this.passwordsShouldMatch
        );
      }
    
      private checkPassword(control: FormControl) {
        return control.value.toString().length >= 5 && control.value.toString().length <= 10
          ? null
          : {'outOfRange': true};
      }
    
      private passwordsShouldMatch(fGroup: FormGroup) {
        return fGroup.get('password').value === fGroup.get('passwordConfirm').value
          ? null : {'mismatch': true};
      }
    }
    

    P.S:checkPassword 控制密码的字符数是否在给定示例中的 510 字符之间

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多