自定义验证程序无法查看“活动表单”中的属性

时间:2017-09-25 17:33:56

标签: angular validation angular2-forms angular-reactive-forms

我已经创建了一个自定义验证器,我想检查密码确认是否有效:

  static cannotContainSpace(control: AbstractControl) : ValidationErrors | null{
    console.log('----- control', control.get('password'));
    console.log('----- control', control.get('passwordConfirmation'));
    if((control.value as string).indexOf(' ') >= 0){
      return {cannotContainSpace : true}
    }
      return null;
  }

你能告诉我为什么在这些控制台日志中我总是得到空值吗?我的表单由reactive form构建,看起来像:

 form = new FormGroup({
    login: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('',
      [
        Validators.required,
        Validators.minLength(3),
        PasswordValidators.cannotContainSpace
      ]),
    passwordConfirmation: new FormControl('', [Validators.required])
  });

enter image description here

2 个答案:

答案 0 :(得分:0)

因为您已经拥有密码控制权。因此,寻找control.get()没有意义。如果您使用control.value,则会看到password控件的当前值。并且passwordConfirmation没有作为验证者的值没有在该控件下注册。

答案 1 :(得分:0)

我将错误本地化 - 它看起来应该是:

  form = new FormGroup({
    login: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('',
      [
        Validators.required,
        Validators.minLength(3),
        PasswordValidators.cannotContainSpace
      ]),
    passwordConfirmation: new FormControl('', [Validators.required])
  }, PasswordValidators.cannotContainSpace);

我们需要在表单中添加validator,而不是在FormControl

中添加String