Himanshu Kumar
Himanshu Kumar

Reputation: 37

Regex containing at-least 3 of the following [0-9], [a-z], [A-Z] or special characters (except $)

I need a regular expression for validating an input field in HTML. The pattern should contain at least three of the followings:

  1. Number [0-9]
  2. Uppercase alphabets [A-Z]
  3. Lowercase alphabets[a-z]
  4. Special characters (except $)
  5. and the minimum length is 6.

Valid Input String:

  1. AAss11
  2. AA11@@
  3. aa11@@
  4. AAss@@

Invalid Input String:

  1. AAAAAA
  2. AA11111
  3. aa111111
  4. AA@@@@@@
  5. AAss11$
  6. 1111111
  7. @@@@@@
  8. $1Asssss
  9. AAss11@$

I have written this regex:

    ^(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[^$])|((?=.*[A-Z])(?=.*[a-z])(?=.
[!#%&'()*+,-./:;<=>?@[\]^_`{|}~])[^$])|((?=.*[A-Z])(?=.*[0-9])(?=.
[!#%&'()*+,-./:;<=>?@[\]^_`{|}~])[^$])|((?=.*[a-z])(?=.*[0-9])(?=.
[!#%&'()*+,-./:;<=>?@[\]^_`{|}~])[^$])).{6,16}$

Upvotes: 1

Views: 961

Answers (1)

user557597
user557597

Reputation:

You could do all the iterations (3 of 4). If ECMAScript new comes out, and
it supports conditionals (?(cond)yes|no) this is greatly simplified.

Here it is, out-of-order :

^(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])|(?=.*[0-9])(?=.*[a-z])(?=.*[!"#%&'()*,\-./:;?@[\]_{}])|(?=.*[0-9])(?=.*[A-Z])(?=.*[!"#%&'()*,\-./:;?@[\]_{}])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!"#%&'()*,\-./:;?@[\]_{}]))[0-9a-zA-Z!"#%&'()*,\-./:;?@[\]_{}]{6,16}$

Expanded view

 ^ 
 (?:
      (?= .* [0-9] )
      (?= .* [a-z] )
      (?= .* [A-Z] )
      #(?= .*[!"#%&'()*,\-./:;?@[\]_{}] )

   |  
      (?= .* [0-9] )
      (?= .* [a-z] )
      #(?= .*[A-Z] )
      (?= .* [!"#%&'()*,\-./:;?@[\]_{}] )

   |  
      (?= .* [0-9] )
      #(?= .*[a-z] )
      (?= .* [A-Z] )
      (?= .* [!"#%&'()*,\-./:;?@[\]_{}] )

   |  
      #(?= .*[0-9] )
      (?= .* [a-z] )
      (?= .* [A-Z] )
      (?= .* [!"#%&'()*,\-./:;?@[\]_{}] )

 )
 [0-9a-zA-Z!"#%&'()*,\-./:;?@[\]_{}]{6,16} 
 $ 

JS sample

var RxPwd = new RegExp("^(?:(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])|(?=.*[0-9])(?=.*[a-z])(?=.*[!\"#%&'()*,\\-./:;?@[\\]_{}])|(?=.*[0-9])(?=.*[A-Z])(?=.*[!\"#%&'()*,\\-./:;?@[\\]_{}])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!\"#%&'()*,\\-./:;?@[\\]_{}]))[0-9a-zA-Z!\"#%&'()*,\\-./:;?@[\\]_{}]{6,16}$", "mg");

var strPwdTest = 
// Should pass
"AAss11\n"  +
"AA11@@\n"  +
"aa11@@\n"  +
"AAss@@\n"  +
// Should fail
"AAAAAA\n"  +
"AA11111\n"  +
"aa111111\n"  +
"AA@@@@@@\n"  +
"AAss11$\n"  +
"1111111\n"  +
"@@@@@@\n"  +
"$1Asssss\n"  +
"AAss11@$\n";

var match;

while ( match = RxPwd.exec( strPwdTest ) )
{
    console.log( match[0], "\t ..Passed" );
}

Upvotes: 2

Related Questions