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

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...