验证密码并确认密码

时间:2019-08-07 07:14:59

标签: angular typescript

我希望我的密码和确认密码应该与输入的值进行比较。 当我在两个密码中输入相同的值并确认密码时,这也显示“密码不匹配”错误

组件

validate(): boolean {
    this.appErrors = [];

    if (this.objAppUser.UserName == '') {
      this.appErrors.push({ Title: 'User name cannot be blank.' });
    }
    if (this.objAppUser.LoginName == '') {
      this.appErrors.push({ Title: 'Login name cannot be blank.' });
    }
    if (this.objAppUser.Password == '') {
      this.appErrors.push({ Title: 'Password cannot be blank.' });
    }    
    if (this.objAppUser.Password !== this.objAppUser.ConfirmPassword) {
      this.appErrors.push({ Title: 'Password does not match.' });
    }
    if (this.objAppUser.UserCategoryId == 0) {
      this.appErrors.push({ Title: 'UserCategory name cannot be blank.' });
    }

    if (this.appErrors.length > 0) {
      return false;
    }
    else {
      return true;
    }
  }

html

  <div>
                    <mat-form-field class="width-size">
                        <input type="password" matInput [(ngModel)]="objAppUser.password" placeholder="Password" name="passwordCtrl">
                    </mat-form-field>
                </div>

                <div>
                    <mat-form-field class="width-size">
                        <input type="password" matInput placeholder="Confirm Password" name="confirmpasswordCtrl">
                    </mat-form-field>
                </div>

1 个答案:

答案 0 :(得分:0)

您可以使用: ngx-custom-validators ,这会使您的工作变得很简单(对于所有类型的自定义验证也是如此)

有了这个,我们要做的就是[equalTo]="password"

HTML

<form [formGroup]='changePasswordForm' novalidate>
    <div class="ele">
        <label>New Password</label>
        <input type="password" ngModel name="password" #password="ngModel" required>
        <p *ngIf="password.errors?.required">required error</p>
    </div>
    <div class="ele">
        <label>Confirm Password</label>
        <input type="password" ngModel name="certainPassword" #certainPassword="ngModel" [equalTo]="password">
        <p *ngIf="certainPassword.errors?.equalTo">equalTo error</p>
    </div>
</form>

WORKING DEMO (反应式+ TemplateDriven)