Sergey Metlov
Sergey Metlov

Reputation: 26291

Password validation regexp

I'm trying regexp for password validation

^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,}$

It restricts at least 1 digit, 1 upper and 1 lower case letter, doesn't it?
So why the following results as true?

(new RegExp('^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,}$')).test('aaAAffffaAfDvad')

But the next one false?

(new RegExp('^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,}$')).test('aaAA112')

Upvotes: 1

Views: 1274

Answers (3)

Bruno
Bruno

Reputation: 5822

Probably not the most efficient way of doing it but quite extensible.

requirements = [ /\d/, /[A-Z]/, /[a-z]/, /^.{6,20}$/ ];

function passwordValid( password ) {
    var i = requirements.length;

    while( i-- ) {
        if( !requirements[i].test( password ) ) return false;
    }
    return true;
}

Upvotes: 1

freakish
freakish

Reputation: 56467

This is because \ in \d is not escaped correctly:

>>> var x = new RegExp('^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$');
>>> x
/^(?=.*d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$/

>>> var x = new RegExp('^(?=.*\\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$');
>>> x
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$/

You can also utilize this function for proper regexp escaping:

RegExp.escape = function(s) {
    return s.replace( /[-\/\\^$*+?.()|[\]{}]/g, "\\$&" );
};
var x = new RegExp( RegExp.escape( '^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$') );

Upvotes: 2

Nick.T
Nick.T

Reputation: 577

in your JS console (firebug or other) try this :

var re = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$/

then this :

var re2 = new RegExp('^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,20}$')

then you just check the results... You'll see that in re2 the \d is not escaped properly for a regexp but escaped for a string.

EDIT : found Javascript: RegExp not working no matter what my expression is

Upvotes: 1

Related Questions