首页 > 解决方案 > 在 Angular 6 中确认密码验证

问题描述

我只想使用材料组件执行密码确认密码验证 ,如果And .Tried 许多资源无法实现,则会在确认密码字段下方显示错误消息。confirm password field doesn't matchif it is empty

也试过这个视频

这是我正在寻找的材料成分

在此处输入图像描述

HTML

     <mat-form-field >
        <input matInput  placeholder="New password" [type]="hide ? 'password' 
          : 'text'" [formControl]="passFormControl" required>
        <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
          'visibility_off'}}</mat-icon>
        <mat-error *ngIf="passFormControl.hasError('required')">
            Please enter your newpassword
         </mat-error>
      </mat-form-field>

      <mat-form-field >
         <input matInput  placeholder="Confirm password" [type]="hide ? 
              'password' : 'text'" [formControl]="confirmFormControl" 
                    required>
         <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
                'visibility_off'}}</mat-icon>
         <mat-error *ngIf="confirmFormControl.hasError('required')">
          Confirm your password
          </mat-error>
      </mat-form-field>

TS

     import {Component, OnInit } from '@angular/core';
     import {FormControl, FormGroupDirective, NgForm, Validators} from 
             '@angular/forms';
     import {ErrorStateMatcher} from '@angular/material/core';

     @Component({
            selector: 'asd-set-pass',
            templateUrl: './set-pass.component.html',
             styleUrls: ['./set-pass.component.css']
         })

       passFormControl = new FormControl('', [
            Validators.required,
        ]);
        confirmFormControl = new FormControl('', [
            Validators.required,
            ]);

             hide =true;

       }

它正在验证以下条件 1) 如果密码和确认密码字段为空,则显示错误文本。

我想与(.ts)文件中的字段进行比较,例如它如何验证空字段,如果确认密码字段为空,则会出现错误。

标签: angularangular-materialangular-forms

解决方案


这个问题可以通过以下两个答案的组合来解决:https ://stackoverflow.com/a/43493648/6294072和https://stackoverflow.com/a/47670892/6294072

因此,首先,您需要一个自定义验证器来检查密码,如下所示:

checkPasswords: ValidatorFn = (group: AbstractControl):  ValidationErrors | null => { 
  let pass = group.get('password').value;
  let confirmPass = group.get('confirmPassword').value
  return pass === confirmPass ? null : { notSame: true }
}

您将为您的字段创建一个表单组,而不仅仅是两个表单控件,然后为您的表单组标记该自定义验证器:

this.myForm = this.fb.group({
  password: ['', [Validators.required]],
  confirmPassword: ['']
}, { validators: this.checkPasswords })

然后如其他答案中所述,mat-error仅显示FormControl是否无效,因此您需要一个错误状态匹配器:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control?.invalid && control?.parent?.dirty);
    const invalidParent = !!(control?.parent?.invalid && control?.parent?.dirty);

    return invalidCtrl || invalidParent;
  }
}

在上面您可以调整何时显示错误消息。我只会在password触摸该字段时显示消息。我还想在上面required从字段中删除验证器confirmPassword,因为如果密码不匹配,表单无论如何都是无效的。

然后在组件中,创建一个新的ErrorStateMatcher

matcher = new MyErrorStateMatcher();

最后,模板如下所示:

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput placeholder="New password" formControlName="password" required>
    <mat-error *ngIf="myForm.hasError('required', 'password')">
      Please enter your new password
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Confirm password" formControlName="confirmPassword" [errorStateMatcher]="matcher">
    <mat-error *ngIf="myForm.hasError('notSame')">
      Passwords do not match
    </mat-error>  
  </mat-form-field>
</form>

这是上面代码的演示:StackBlitz


推荐阅读