【问题标题】:Password is not matched with pattern in Angular CLI密码与 Angular CLI 中的模式不匹配
【发布时间】:2019-11-15 18:22:27
【问题描述】:

我的密码验证有问题,我正在使用正则表达式,例如:

'(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])'

我的 ng-form 字段是;

password: ['', [Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])'), Validators.required]]

在 HTML 中,我的输入为;

<div class="form-group">
    <label for="password">Password</label>
    <input type="password" formControlName="password" placeholder="******" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
    <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
      <div *ngIf="f.password.errors">Invalid Password</div>
    </div>
  </div>

其中 f 是函数,例如;

 get f() {
     return this.userForm.controls; 
 }

当我输入密码为:Harun123 时,出现密码无效错误。为什么会这样?

【问题讨论】:

  • 我还在表达式开头加了^

标签: html regex angular passwords


【解决方案1】:

这个问题可以结合这两个答案来解决:

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

checkPasswords(group: FormGroup) { // here we have the 'passwords' group
let pass = group.controls.password.value;
let confirmPass = group.controls.confirmPass.value;

return pass === confirmPass ? null : { notSame: true }     
}

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

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

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

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

return (invalidCtrl || invalidParent);
 }
}

在上面你可以调整何时显示错误信息。我只会在触摸密码字段时显示消息。我也想在上面从 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多