Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript : validate upper case and lower case

Is there any option to validate minimum 2 lower case and 2 upper case when checking case ? here is the condition which I am using.

function HasMixedCase(passwd){
    if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
        return true;
    else
        return false;
}

Demo: http://jsfiddle.net/Ku4mg/

like image 420
Mo. Avatar asked Nov 25 '25 16:11

Mo.


2 Answers

Edited to factor in plalx's comment:

var m;
if( !(m = passwd.match(/[a-z]/g)) || m.length < 2) return false;
if( !(m = passwd.match(/[A-Z]/g)) || m.length < 2) return false;
return true;

Trying to do too much in a single regex is a recipe for disaster, with the most common result being catastrophic backtracking.

Similarly, it makes your code more readable to do one thing at a time.

like image 145
Niet the Dark Absol Avatar answered Nov 28 '25 06:11

Niet the Dark Absol


Altough @NietTheDarkAbsol's answer shows a perfectly valid way I would advise you to avoid doing too much in your functions. Do not be afraid of splitting logic into multiple maintainable functions.

function textCaseStats(text) {
    return {
        upper: (text.match(/[a-z]/g) || []).length,
        lower: (text.match(/[A-Z]/g) || []).length
    };
}

function hasMixedCase(password) {
    var caseStats = textCaseStats(password);

    return caseStats.lower >= 2 && caseStats.upper >= 2;
}
like image 43
plalx Avatar answered Nov 28 '25 04:11

plalx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!