Reputation: 41
I am trying to make a function that checks for special characters such as !@#$%^&*~ when I input a password. I've been using regular expressions to check for everything else, but does anyone know how I can make it so the function checks the password for at least one of these special characters?
Here's what I have:
function validateEmail(email)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/;
return emailPattern.test(email);
}
function validatePassword(password)
{
var passwordPattern = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])./;
return passwordPattern.test(password)
}
function validate()
{
var email = user.email.value;
if(validateEmail(user.email.value))
user.validEmail.value = "OK";
else
user.validEmail.value = "X";
if(validatePassword(user.password.value))
user.validPassword.value = "OK";
else
user.validPassword.value = "X";
}
Upvotes: 0
Views: 796
Reputation: 32158
You can match any non-(letters, digits, and underscores) characters with \W
.
So to check the password if has any special character you can just simply use:
if (password.match(/\W/)) {
alert('you have at least one special character');
}
to use it in your function you can replace the whole regex with:
var passwordPattern = /^[\w\W]*\W[\w\W]*$/;
that will return true if the string has at least one special character.
Upvotes: 1