PDA

View Full Version : Javascript Regex Validation.



cancer10
11-01-2011, 02:22 AM
Hello

I need some help with validating the password strength of my form.

I am actually looking for a regular expression that could force the users to have at least 2 of the following:

1. Upper and lower case.
2. Numbers
3. Symbols.


Thanks in advance for any help

djr33
11-01-2011, 02:48 AM
Maybe you could do that, but "at least 2" is a complicated expression. You could have A&B||B&C||A&C, but that would be a lot to write out.
I would just suggest making three validations, then checking to see if at least 2 were valid. You could even use a single counter variable and see if in the end that is >=2. (For each validation step, add one to the variable.)

This will be more reliable if you do it serverside, although I suppose if a user wants to avoid your suggested security regulations for passwords, that's not really your problem. (If they turn off Javascript, they can avoid the check.)

cancer10
11-01-2011, 05:35 AM
Hi

Someone suggested me this solution and I am sharing it with you all :)



<script>
function validate(){

var pw = 'dddDd##';

if ( ( pw.match(/[a-z]/) && pw.match(/[A-Z]/) ? 1 : 0 ) +
( pw.match(/\d/) ? 1 : 0 ) +
( pw.match(/[\`\~\!\@\#\$\%\^\&\*\(\)\_\-\+\=\[{}\\\}\:\;\"\'\<\,\>\.\?\/]/) ? 1 : 0 )
>= 2 )
{
alert('true');
} else {
alert('false');
}
}

</script>
<input type="button" onclick="validate()" />

djr33
11-01-2011, 05:52 AM
That's a creative way to do it (although the code looks a little messy, but it's fine).
One note is that you can do a list of symbols like that, but you might want to do it the other way: check to find a specific character that is NOT a digit and NOT a letter. I'm not sure of the exact regex syntax for that, but it should be a little shorter to code and more accurate. (Of course it is a secondary problem if a user uses a symbol that is not allowed by the system, but you should deal with that serverside and reject the password then.)

cancer10
11-01-2011, 05:55 AM
Thanks for your input sir.

jscheuer1
11-01-2011, 06:04 AM
A bit more efficient:


<script>
function validate(){
var pw = 'dddDd##';
if(
( /[a-z]/.test(pw) && /[A-Z]/.test(pw)? 1 : 0 ) +
( /\d/.test(pw)? 1 : 0 ) +
( /[!-\/:-@[-`{-~]/.test(pw)? 1 : 0 )
> 1 ){
alert('true');
} else {
alert('false');
}
}
</script>
<input type="button" onclick="validate()" />

But that (your original criteris) means that:

#1

would pass. Perhaps requiring at least 6 characters would be good too:


<script>
function validate(){
var pw = 'dddD##';
if(
( /[a-z]/.test(pw) && /[A-Z]/.test(pw)? 1 : 0 ) +
( /\d/.test(pw)? 1 : 0 ) +
( /[!-\/:-@[-`{-~]/.test(pw)? 1 : 0 )
> 1 && pw.length > 5){
alert('true');
} else {
alert('false');
}
}
</script>
<input type="button" onclick="validate()" />