Need to match at least one letter, at least one number, and at least one non-alphanum
Hey all,
This is my first post on this site so forgive me if I make any formatting mistakes.
I'm trying to make a password validator that only allows passwords with at least one letter, at least one number, and at least one non-alphanumeric character. Here's what I'm using right now but I can't seem to match the non-alphanumeric character.
Code:
function ValidatePassword(password, password_c, msg)
{
if (notEmpty(password, "Enter a password"))
{
if (password.value === password_c.value)
{
if (password.value.match("\W|_"))
{
if (/\d/.test(password.value) && /[a-zA-Z]/.test(password.value))
{
return true;
} else {
alert(msg);
}
} else {
alert("Must have a special character in your password");
}
} else {
alert("Passwords don't match");
}
}
return false;
}
I got the regex codes from different sites so I'm guessing that's why they aren't working together. Any help is much appreciated!
I figured it out. For some reason the "password.value.match("\W|_")" wasn't working correctly. I switched it to "/\W/.test(password.value)" and that worked. Does anyone know how I can combine this into one regular expression?
Code:
function ValidatePassword(password, password_c, msg)
{
if (notEmpty(password, "Enter a password"))
{
if (password.value === password_c.value)
{
if(/\W/.test(password.value))
{
if (/\d/.test(password.value) && /[a-zA-Z]/.test(password.value))
{
return true;
} else {
alert(msg);
}
} else {
alert("Must have a special character in your password");
}
} else {
alert("Passwords don't match");
}
}
return false;
}
You have to use assertions (An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed)
Code:
var rgx=/(?=.*\d)(?=.*[a-zA-Z])(?=.*[^0-9a-zA-Z])/
// Test
var toTest=['azert7ui@i','uiop5','4561238|y','jhkj','7989io','456@456'];
for (i=0;i<toTest.length;i++) alert(toTest[i]+' '+rgx.test(toTest[i]));
We test, at first, one digit (?=.*\d) which can be preceded with something or not. Then a alphabetic(*) characters and a non-alphabetic characters. This regular expression which do not change the matching position could be completed with a test about the minimal length of the password...
The test is wrong with \ which as a special meaning in a string.
(*) The use of \w ("word" character is any letter or digit !) which duplicate digit is wrong (the test is true with only digits and special characters) !
Last edited by 007Julien; 02-20-2013 at 08:53 AM.
Reason: complement
Bookmarks