1

I've a reactive forms validation for a password, and the pattern is the following:

new RegExp('^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$^+=!*()@%&]).{8,50}$');

My goal is to validate the string so it is:

  • Between 8 & 50 characters
  • Has a lower case letter
  • Has an upper case letter
  • Has a number
  • And has a symbol

For some reason, it works like a charm, but if I enter a password that starts with a single number, the validation fails.

What am I doing wrong? Example passwords:

1dD5a971# -- doesn't match

11dD5a971# -- does match

The angular code:

 static PASSWORD_PATTERN = new RegExp('^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$^+=!*()@%&]).{8,50}$');
this.form= fb.group({
            user: [...],
            password: ['', [Validators.compose([
                Validators.required,
                Validators.min(8),
                Validators.max(50),
                Validators.pattern(AddUserComponent.PASSWORD_PATTERN)
            ])]]
        };

Thank you in advance.

Hienz
  • 688
  • 7
  • 21

1 Answers1

3

I 'm not a regex expert but it may be much better if you make a multi pattern rather than just a complex pattern,the goal was for me to keep it simple as possible and you can have a different message base of the patterns.

    this.form = fb.group({
      password: [
        "",
        [
          Validators.required, 
          Validators.minLength(8),
          Validators.maxLength(50),
          Validators.pattern(/[A-Z]/),
          Validators.pattern(/[a-z]/),
          Validators.pattern(/[0-9]/),
          Validators.pattern(/[!@#$]/),
         ]
      ]
    });

demo

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91