Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - How to validate password strength with Angular 5 Validator Pattern

I need to validate the strength of a password input form field. The requirements are:

  • at least one lowercase char
  • at least one uppercase char
  • at least one number
    (no matter the order)

What I have searched and tried so far goes below, the results are inconsistent.

It seems to validate the order of the regex validation.
What I need is to just check if at least one of the char "types" are present.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'signup',
    templateUrl: './signup.component.html',
    styleUrls: ['./signup.component.scss']
})
export class SignupComponent {

    form: FormGroup;

    constructor() {
        this.init();
    }

    init() {
        this.form = this.fb.group({
            name: ['', [Validators.required]],
            email: ['', [Validators.required, Validators.email],
            password: ['', [
                Validators.required, 
                Validators.pattern('((?=.*d)(?=.*[a-z])(?=.*[A-Z]).{8,30})')
            ]]
        }); 
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I took a stab at this with Angular's built-in pattern validator and was able to come up with the following that checks for:

  • At least 8 characters in length
  • Lowercase letters
  • Uppercase letters
  • Numbers
  • Special characters

    password: [
      '',
      [
        Validators.required,
        Validators.pattern('(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-zd$@$!%*?&].{8,}')
       ]
    ]
    

I'll add that I'm by no means a regex expert. This is simply what worked for me for a closely related case to the OP. Maybe it will help someone else. Mozilla's documentation helped a lot in figuring this out, specifically the Writing a regular expression pattern section.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...