首页 > 解决方案 > 如何在angular2中验证新密码并确认密码

问题描述

我有 2 个字段,密码和确认密码。那么,我如何验证两者?HTML:

<div class="mb-4  col-lg-6">
              <label >Password
                <span class="required">*</span>
              </label>
              <input class="form-control" type="password" placeholder="Password"
formControlName="Password">
              <control-messages [control]="controls.Password" class="errorMessage"></control-messages>
              <div class="errorMessage" *ngIf="validationPassBlank==1">{{errorMessage}}</div>
             <div class='required' *ngIf="validationError == 1">{{errorMessage}}</div>
            </div>

标签: angular

解决方案


做这样的事情。

private buildForm(): void {
    this.form = this.fb.group({
      password: [null, Validators.required],
      repeat: [null, Validators.required]
    }, {validator: this.checkIfMatchingPasswords('password', 'repeat')});
}


private checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
    return (group: FormGroup) => {
      const passwordInput = group.controls[passwordKey],
        passwordConfirmationInput = group.controls[passwordConfirmationKey];
      if (passwordInput.value !== passwordConfirmationInput.value) {
        return passwordConfirmationInput.setErrors({notEquivalent: true});
      } else {
        return passwordConfirmationInput.setErrors(null);
      }
    };
  }

并在表单的模板里面。

<p *ngIf="form.get('repeat')?.errors?.notEquivalent">Passwords did not match</p>
<p *ngIf="form.get('repeat')?.errors?.required">Confirm password is required</p>

推荐阅读