如何验证新密码并确认angular2中的密码

Bhr*_*jni 1 angular

我有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>
Run Code Online (Sandbox Code Playgroud)

Anu*_*ara 5

做这样的事情。

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);
      }
    };
  }
Run Code Online (Sandbox Code Playgroud)

并在模板里面的表格。

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