Reputation: 11452
I have regular expression which tests following rules,
My attempt is this,
/^([a-zA-Z+]+[0-9+]+[!@#$%^&*])$/
This works fine as for most cases except if I add more then one alpha-numeric chars.
Tests
The last test should get Passed but it fails. I know where things are wrong but couldn't get hang of the regex magic. My thoughts about what is wrong is,
[0-9+] // This + sign shows that you can have more then 1 of that range of numerics
Where,
[!@#$%^&*] // Does not have the + sign
I tried,
[!@#$%^&*+] // Does not have the + sign
[!@#$%^&*]+ // Does not have the + sign
Both didn't work. What am I missing?
Upvotes: 0
Views: 153
Reputation: 2988
Try the following. It will work if a characters should be first, numerics should be second and alpahanumerics should be next.
/^[a-zA-Z]+[1-9]+[!@#$%^&*]+$/
Upvotes: 0
Reputation: 50905
Depending on what you actually need, from your confusing description of your situation, here are two regexes that I hope help. This first one requires that the password start with at least 1 Alphabetic character, have at least 1 Numeric character second, then at least 1 Special character last.
/^([a-zA-Z]+[0-9]+[!@#$%^&*]+)$/
If you don't require the characters to come in a specific order, you can try this regex:
/(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9])(?=[^!@#$%^&*]*[!@#$%^&*])/
This one simply requires that there be at least 1 Alphabetic character, at least 1 Numeric character, and at least 1 Special character, occur in the password in any order.
Upvotes: 1
Reputation: 298246
Why do you need to mash it all into one regex?
function test_password(password) {
if (password.length < 2) return false; // Minimum length
if (!/[0-9]/g.test(password)) return false; // Needs a number
if (!/[a-z]/gi.test(password)) return false; // Needs a letter
if (!/[^a-z0-9]/gi.test(password)) return false; // Needs a special char
return true;
}
Upvotes: 1