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!

1

2 Answers 2

4

You can add another lookahead in your regex:

/^(?=.*[0-9])(?=(?:[^A-Z]*[A-Z]){2})(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,12}$/;
Sign up to request clarification or add additional context in comments.

Comments

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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.