Siju Mohan MM
Siju Mohan MM

Reputation: 143

Regex satisfying multiple conditions

First of all, I have found several examples relating to my query. But none of them was helpful.

Could you please help me to create a regex which satisfies following 3 conditions:

  1. String must contain exactly one alphabetic character
  2. String must contain digits
  3. String must be 9 length

I believe following regex can be used to validate the 3rd condition: \A(?=\w{9,9}\z)

But I was unable to figure out how to combine multiple conditions.

Upvotes: 3

Views: 3544

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can use the following regex:

^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*)(?=.*[0-9].*).{9}$

Or, if you do not allow anything other than digits and letters:

^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*)(?=.*[0-9].*)[0-9a-zA-Z]{9}$

Demo.

Explanation:

  • ^ - String start
  • (?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*) - Ensure there is only 1 letter in the 9-character string
  • (?=.*[0-9].*) - Ensure that there are digits
  • [0-9a-zA-Z]{9} - The string is 9 characters long (only allowing numbers and characters) (or .{9} - will allow any characters)
  • $ - String end

Mind that [^\r\n] is added for a more reliable testing on regex101, if you test individual strings (not multiline lists), you can just use ^(?=[^a-zA-Z]*[a-zA-Z][^a-zA-Z]*)(?=.*[0-9].*)[0-9a-zA-Z]{9}$.

function isValidPassword(str) {
   return /^(?=[^\r\na-zA-Z]*[a-zA-Z][^\r\na-zA-Z]*$)(?=.*[0-9].*$)[0-9a-zA-Z]{9}$/.test(str);
}

document.getElementById("res").innerHTML = "3445345f3 is " + isValidPassword('3445345f3') + "<br>222222222 is " + isValidPassword("222222222");
<div id="res"/>

Upvotes: 4

Related Questions