Reputation: 37
I need a regular expression for validating an input field in HTML. The pattern should contain at least three of the followings:
Valid Input String:
- AAss11
- AA11@@
- aa11@@
- AAss@@
Invalid Input String:
- AAAAAA
- AA11111
- aa111111
- AA@@@@@@
- AAss11$
- 1111111
- @@@@@@
- $1Asssss
- 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
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