简体   繁体   中英

Checking form for special characters in JavaScript.

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";
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM