JavaScript to validate password
Can anyone help me in writing a regular expression on the following description?
The password contains characters from at least three of the following five categories:
- English uppercase characters (A - Z)
- English lowercase characters (a - z)
- Base 10 digits (0 - 9)
- Non-alphanumeric 开发者_StackOverflow中文版(For example: !, $, #, or %)
- Unicode characters
The minimum length of the password is 6.
Better way to deal this is to split each of the conditions and have a regex for each of the condition. Then count how many have been satisfied for entered password. In this way you can even tell user if the password is average, meets criteria or a very strong password.
if (password.length < 6) {
alert("password needs to be atleast 6 characters long");
}
var count = 0;
//UpperCase
if( /[A-Z]/.test(password) ) {
count += 1;
}
//Lowercase
if( /[a-z]/.test(password) ) {
count += 1;
}
//Numbers
if( /\d/.test(password) ) {
count += 1;
}
//Non alphas( special chars)
if( /\W/.test(password) ) {
count += 1;
}
if (count < 3) {
alert("password does not match atleast 3 criterias");
}
Not sure how to match unicode characters using regex. Rest all conditions are available above.
[A-Za-z!$#%\d\u0100]{6}
matches aS1%eĀ
.
\u0100
is for Ā. You can insert other Unicode codes that you need. You can find them here.
EDIT: For minimum 6 characters the correct regex is [A-Za-z!$#%\d\u0100]{6,}
.
EDIT 2: To include a range of Unicode characters (let that be Latin Extended-B), the regex should look like ^[A-Za-z!$#%\d\u0100-\u017f]{6,}$
. You can find the Unicode code ranges here.
EDIT 3: I've developed a tiny function that checks whether the given password conforms to the criterias. You need to define the unicode range in the function.
function isValidPassword(password) {
var unicodeRange = "\\u0100-\\u0105";
var criteria = ["A-Z","a-z","\\d","!$#%",unicodeRange];
// check whether it doesn't include other characters
var re = new RegExp("^[" + criteria.join("") +"]{6,}$");
if(!re.test(password)) return false;
var minSatisfiedCondition = 3;
var satisfiedCount = 0;
for( var i=0; i < criteria.length; i++) {
re = new RegExp("[" + criteria[i] + "]");
if(re.test(password)) ++satisfiedCount;
}
return (satisfiedCount >= minSatisfiedCondition);
}
There is a working sample here.
精彩评论