自定义密码匹配验证器在angular5中不起作用

时间:2019-01-02 09:29:26

标签: angular validation angular5 angular2-forms customvalidator

我正在实现自定义验证程序以匹配组件中的密码。

这是我的component.ts表单声明

this.addUserForm = new FormGroup({
  firstname: new FormControl('', [Validators.required]),
  lastname: new FormControl('', [Validators.required]),
  city: new FormControl(),
  address: new FormControl(),
  email: new FormControl('', [Validators.required, Validators.email]),
  password: new FormControl('', [Validators.required, Validators.minLength(6)]),
  confirm_password: new FormControl('', [Validators.required, ConfirmPasswordValidator.MatchPassword]),
  role: new FormControl('', [Validators.required]),
  phone: new FormControl(),
  companyCode: new FormControl(this.local_storage.getCurrentUser().companyCode, [Validators.required])
});

这是我的custom.validator.ts

import { AbstractControl } from '@angular/forms';

export class ConfirmPasswordValidator {
static MatchPassword(control: AbstractControl) {
    let password = control.get('password').value;
    let confirmPassword = control.get('confirm_password').value;

    if (password != confirmPassword) {
        console.log('false')
        control.get('confirmPassword').setErrors({ ConfirmPassword: true });
    } else {
        return null
    }
  }
 }

这是我的component.html输入部分

 <label class="col-form-label">Password</label>
        <div class="form-group row">
          <div class="col-sm-10">
            <input type="password" class="form-control" formControlName="password">
            <div class="alert alert-danger" *ngIf="addUserForm.get('password').touched && addUserForm.get('password').invalid && addUserForm.get('password').errors.required">
              Password is required
            </div>
            <div class="alert alert-danger" *ngIf="addUserForm.get('password').touched && addUserForm.get('password').invalid && addUserForm.get('password').errors.minlength && !addUserForm.get('password').errors.required">
              Password length must be greater than 6
            </div>
          </div>
        </div>
       <div class="alert alert-danger" *ngIf="addUserForm.get('confirm_password').touched && addUserForm.get('confirm_password').invalid && addUserForm.get('confirm_password').errors.ConfirmPassword">
              Password deesn't match
          </div>

但是它给出了这个错误  property 'value' of null TypeError: Cannot read property 'value' of null at ConfirmPasswordValidator.MatchPassword (user.validator.ts:5) 项目结构和目录非常复杂且庞大,这就是为什么不能共享所有组件和html代码的原因。 我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题。

首先:您将从名为“ password”的控件中获取一个子控件,并从传递给验证器的控件中获取另一个名为“ confirmPassword”的子窗体控件。因此,验证者应该验证的是FormGroup,其中包含这两个表单控件。但是您没有在表单组上设置此验证器。您正在表单控件confirmPassword上进行设置。您需要在随附的表单组上设置此验证器。

第二:验证器不应修改其正在验证的控件。它的唯一责任是返回错误(如果没有错误,则为null)。 Angular将根据您返回的内容设置控件的有效性。所以它的代码应该是

static MatchPassword(control: AbstractControl) {
  const password = control.get('password').value;
  const confirmPassword = control.get('confirm_password').value;

  if (password != confirmPassword) {
    return { ConfirmPassword: true };
  } else {
    return null;
  }
}

或者,更简洁地说:

static MatchPassword(control: AbstractControl) {
  return control.get('password').value != control.get('confirm_password').value ? { ConfirmPassword: true } : null;
}

答案 1 :(得分:0)

表单组验证器

更新MatchPassword以在表单组级别上工作,因此您无需向confirmPassword控件中添加自定义验证器

static MatchPassword(control: AbstractControl) {
    let password = control.get('password').value;
    let confirmPassword = control.get('confirm_password').value;

    if (password != confirmPassword) {
      return { ConfirmPassword: true };
    } else {
        return null
    }
  }

并为formGroup验证器选项添加此验证器

{ validators: ConfirmPasswordValidator.MatchPassword }

stackblitz demo

表单控件验证器

如果要向控件添加验证,以便控件参数为确认密码控件,则需要使用父级来访问表单组并获取密码控件的值

this.form = fb.group({
  password: [null, [Validators.required]],
  confirm_password: [null, [Validators.required, MatchPassword]]
})

MatchPassword验证器

function MatchPassword(control: AbstractControl) {
  let parent = control.parent
  if (parent) {
    let password = parent.get('password').value;
    let confirmPassword = control.value;

    if (password != confirmPassword) {
      return { ConfirmPassword: true };
    } else {
      return null
    }
  } else {
    return null;
  }

stackblitz demo