密码与Angular CLI中的模式不匹配

时间:2019-07-05 06:27:03

标签: html regex angular passwords

我在密码验证方面遇到问题,我正在使用正则表达式,例如;

'(?=.*[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 时,出现无效密码错误。为什么会这样?

1 个答案:

答案 0 :(得分:0)

可以通过结合以下两个答案来解决此问题:

因此,首先,您需要一个自定义验证器来检查密码,看起来像这样

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