Password REGEX with min 6 chars, at least one letter and one number and may contain special characters
Perhaps a single regex could be used, but that makes it hard to give the user feedback for which rule they aren't following. A more traditional approach like this gives you feedback that you can use in the UI to tell the user what pwd rule is not being met:
function checkPwd(str) { if (str.length < 6) { return("too_short"); } else if (str.length > 50) { return("too_long"); } else if (str.search(/\d/) == -1) { return("no_num"); } else if (str.search(/[a-zA-Z]/) == -1) { return("no_letter"); } else if (str.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+]/) != -1) { return("bad_char"); } return("ok");}
following jfriend00 answer i wrote this fiddle to test his solution with some little changes to make it more visual:
and this is the code:
checkPwd = function() { var str = document.getElementById('pass').value; if (str.length < 6) { alert("too_short"); return("too_short"); } else if (str.length > 50) { alert("too_long"); return("too_long"); } else if (str.search(/\d/) == -1) { alert("no_num"); return("no_num"); } else if (str.search(/[a-zA-Z]/) == -1) { alert("no_letter"); return("no_letter"); } else if (str.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+\.\,\;\:]/) != -1) { alert("bad_char"); return("bad_char"); } alert("oukey!!"); return("ok");}
btw, its working like a charm! ;)
best regards and thanks to jfriend00 of course!
A more elegant and self-contained regex to match these (common) password requirements is:
^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d^a-zA-Z0-9].{5,50}$
The elegant touch here is that you don't have to hard-code symbols such as $ @ # etc.
To accept all the symbols, you are simply saying: "accept also all the not alphanumeric characters and not numbers".
Min and Max number of characters requirement
The final part of the regex {5,50}
is the min and max number of characters, if the password is less than 6 or more than 50 characters entered the regex returns a non match.