Angular 5中的自定义密码验证

时间:2018-08-27 16:30:04

标签: angular typescript angular-material password-protection

我正在尝试将自定义密码验证添加到密码字段。密码必须至少包含8个字符,并且至少满足以下两个条件,但不必同时满足所有四个条件:

  • 有数字
  • 具有小写字母
  • 具有大写字母
  • 有特殊字符

我已经参与了验证工作,但是遇到一个问题,如果密码长度超过8个字符,但至少不满足以上两个条件,则错误消息将节目。仅当密码少于8个字符时,才会显示有关字符的错误。

我在SO上进行了搜索,但没有成功实现类似问题的答案。我怀疑我的自定义验证功能与ngModel中的密码不相关的问题。

问题:当密码长度超过8个字符但不满足上述字符要求时,如何显示错误消息并显示在表单字段上?

这是相关的代码。

来自 user-form.html

 <mat-form-field *ngIf="newPassword" fxFlex="100%">
  <input matInput #password="ngModel" placeholder="Password" type="password" autocomplete="password"
         [(ngModel)]="model.password" name="password" minlength="8" (keyup)="validatePassword(model.password)" required>
  <mat-error *ngIf="invalidPassword">
    Password must contain at least two of the following: numbers, lowercase letters, uppercase letters, or special characters.
  </mat-error>
  <mat-error *ngIf="password.invalid && (password.dirty || password.touched)">
    <div *ngIf="password.errors.required">
      Password is required
    </div>
    <div *ngIf="password.errors.minlength">
      Password must be at least 8 characters
    </div>
  </mat-error>
</mat-form-field>

来自 user-form.component.ts

export class UserFormComponent implements OnInit {


  @Input()
  user: User;

  public model: any;
  public invalidPassword: boolean;


  constructor() {}

  ngOnInit() {
    this.model = this.user;
  }


  passwordFails(checks: boolean[]): boolean {
     let counter = 0;
    for (let i = 0; i < checks.length; i++) {
      if (checks[i]) {
        counter += 1;
      }
    }
    return counter < 2;
 }


  validatePassword(password: string) {
    let hasLower = false;
    let hasUpper = false;
    let hasNum = false;
    let hasSpecial = false;

    const lowercaseRegex = new RegExp("(?=.*[a-z])");// has at least one lower case letter
    if (lowercaseRegex.test(password)) {
      hasLower = true;
    }

    const uppercaseRegex = new RegExp("(?=.*[A-Z])"); //has at least one upper case letter
    if (uppercaseRegex.test(password)) {
      hasUpper = true;
    }

    const numRegex = new RegExp("(?=.*\\d)"); // has at least one number
    if (numRegex.test(password)) {
      hasNum = true;
    }

    const specialcharRegex = new RegExp("[!@#$%^&*(),.?\":{}|<>]");
    if (specialcharRegex.test(password)) {
      hasSpecial = true;
    }

    this.invalidPassword = this.passwordFails([hasLower, hasUpper, hasNum, hasSpecial]);
  }
}

3 个答案:

答案 0 :(得分:0)

您正在将 Private Sub CboTimestamp_AfterUpdate() Dim myTimestamp As String myTimestamp = "SELECT * FROM master_demand_table where ([timestamp] = " & Me.Cbotimestamp ")" Me.Master_Demand_table__subform.Form.RecordSource = myTimestamp Me.Master_Demand_table__subform.Form.Requery End Sub 的值传递给build.options函数

boolean

将功能更改为以下功能,如果密码不符合其中一项条件,则返回true。

passwordFails

在dom中,您可以添加另一个条件来检查invalidPassword

this.invalidPassword = this.passwordFails([hasLower, hasUpper, hasNum, hasSpecial]);

答案 1 :(得分:0)

Stackblitz Demo

Component.html

<div class="error-text" *ngIf="myForms.get('password').hasError('passwordStrength')">
    {{myForms.get('password').errors['passwordStrength']}}
</div>

Component.ts

this.myForms = fb.group({
      password: [null, Validators.compose([
        Validators.required, Validators.minLength(8), PasswordStrengthValidator])]
});

password-strength.validators.ts

import { AbstractControl, ValidationErrors } from "@angular/forms"

export const PasswordStrengthValidator = function (control: AbstractControl): ValidationErrors | null {


let value: string = control.value || '';
  let msg="";
  if (!value) {
    return null
  }

  let upperCaseCharacters = /[A-Z]+/g;
  let lowerCaseCharacters = /[a-z]+/g;
  let numberCharacters = /[0-9]+/g;
  let specialCharacters = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
  if (upperCaseCharacters.test(value) === false || lowerCaseCharacters.test(value) === false || numberCharacters.test(value) === false || specialCharacters.test(value) === false) {
return {
  passwordStrength: 'Password must contain at least two of the following: numbers, lowercase letters, uppercase letters, or special characters.'
}

}

}

答案 2 :(得分:0)

我进一步研究了这个问题,看看是否可以弄清楚如何在Angular中使用Validators。我终于可以通过以下更新来做到这一点:

创建 password-validator.directive.ts

import { Directive, forwardRef, Attribute} from "@angular/core";
import { Validator, AbstractControl, NG_VALIDATORS} from "@angular/forms";

@Directive({
  selector: '[validatePassword]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => PasswordValidator), multi: true}
  ]
})

export class PasswordValidator implements Validator {
  constructor (
    @Attribute('validatePassword')
    public invalidPassword: boolean
  ) {}

  validate(ctrl: AbstractControl): {[key: string]: any} {
    let password = ctrl.value;

    let hasLower = false;
    let hasUpper = false;
    let hasNum = false;
    let hasSpecial = false;

    const lowercaseRegex = new RegExp("(?=.*[a-z])");// has at least one lower case letter
    if (lowercaseRegex.test(password)) {
      hasLower = true;
    }

    const uppercaseRegex = new RegExp("(?=.*[A-Z])"); //has at least one upper case letter
    if (uppercaseRegex.test(password)) {
      hasUpper = true;
    }

    const numRegex = new RegExp("(?=.*\\d)"); // has at least one number
    if (numRegex.test(password)) {
      hasNum = true;
    }

    const specialcharRegex = new RegExp("[!@#$%^&*(),.?\":{}|<>]");
    if (specialcharRegex.test(password)) {
      hasSpecial = true;
    }

    let counter = 0;
    let checks = [hasLower, hasUpper, hasNum, hasSpecial];
    for (let i = 0; i < checks.length; i++) {
      if (checks[i]) {
        counter += 1;
      }
    }

    if (counter < 2) {
      return { invalidPassword: true }
    } else {
      return null;
    }



  }

}

user-form.component.html 中更新:

<mat-form-field *ngIf="newPassword" fxFlex="100%">
  <input matInput #password="ngModel" placeholder="Password" type="password" autocomplete="password"
         [(ngModel)]="model.password" name="password" minlength="8" validatePassword="password" required>
  <mat-error *ngIf="password.invalid && (password.dirty || password.touched)">
    <div *ngIf="password.errors.invalidPassword">
      Password must have two of the four: lowercase letters, uppercase letters, numbers, and special characters
    </div>
    <div *ngIf="password.errors.required">
      Password is required
    </div>
    <div *ngIf="password.errors.minlength">
      Password must be at least 8 characters
    </div>
  </mat-error>
</mat-form-field>

user-form.module.ts 中更新:

import {PasswordValidator} from "../password-validator.directive"; //imported to modules

@NgModule({
  imports: [
    //some modules
  ],
  declarations: [
    // some modules
    PasswordValidator // added this to declarations
  ],
  exports: [
    // stuff
  ],
  providers: [
    //stuff
  ]
})
export class UserFormModule { }