1

Pls help me with regular expression. I have method to validate password using regex:

/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/;

I need to add to this condition that password has to contain 2 capital letters.

Thx for help!

Chris
  • 785
  • 5
  • 12
  • 29
  • 1
    Search is your friend. See: [Regular expression for a string that must contain minimum 14 characters, where at minimum 2 are numbers, and at minimum 6 are letters](http://stackoverflow.com/a/5527428/433790) – ridgerunner Nov 20 '13 at 19:40

2 Answers2

4

You can add another lookahead in your regex:

/^(?=.*[0-9])(?=(?:[^A-Z]*[A-Z]){2})(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/;
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

This is a really ugly way of checking password syntax. Your code would be much easier to read and debug if you split your checks into multiple steps.

For example:

/* Check for at least 2 capital letters */
if (!(/[A-Z][^A-Z]*[A-Z]/.test(password))) {
  alert("Your password must contain at least two capital letters");
  return false;
}
/* Check for at least 2 lower case letters */
if (!(/[a-z][^a-z]*[a-z]/.test(password))) {
  alert("Your password must contain at least two lower case letters");
  return false;
}
/* Check for at least one digit */
if (!(/[0-9]/.test(password))) {
  alert("Your password must contain at least one digit");
  return false;
}
... etc ...
r3mainer
  • 23,981
  • 3
  • 51
  • 88