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.

12
  • 1
    I think the pattern works right? regex101.com/r/tv9IIM/1 Commented Jan 22, 2020 at 9:31
  • Yes, I'll update my question in a sec with the code I use. Commented Jan 22, 2020 at 9:31
  • It should work with the current code. Commented Jan 22, 2020 at 9:36
  • Are the two \ in the first grop intentional? Commented Jan 22, 2020 at 9:36
  • @chrnx Certainly yes. Though surely it can be written as static PASSWORD_PATTERN = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[#$^+=!*()@%&]).{8,50}$/; Commented Jan 22, 2020 at 9:37

1 Answer 1

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 🚀

Sign up to request clarification or add additional context in comments.

2 Comments

All {1,}s are redundant here, consider removing.
Well, it works. In addition I can customize even more the error message to the user. Thanks dude.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.