views:

87

answers:

2

Hi, I am new to regular expressions.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 (For example: !, $, #, or %)
  • Unicode characters

The minimum length of the password is 6. Please help me in this..

Regards, Abhimanyu

A: 

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.

Sachin Shanbhag
This is a comment, not an answer. (Completely agree, btw.)
T.J. Crowder
Updated the answer too
Sachin Shanbhag
Thanks Sachin,it works fine
Abhimanyu
+1  A: 

[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.

Zafer
With this regular expressions you don't know if at least 3 criteria of the OP are matching.
splash
@splash: Yes, you're right. I've edited my answer and put a validation function.
Zafer