将验证器添加到被动表单时出错

时间:2017-08-07 09:06:36

标签: angular validation typescript

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

 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时,它开始工作 - 为什么会这样?

2 个答案:

答案 0 :(得分:2)

根据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
  );
}

答案 1 :(得分:0)

我不确定您使用的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个字符之间