Search code examples
javascriptformsvalidationspecial-characters

Check for special characters (, ; .) while validating a form with JavaScript


I tried to insert this piece of code (which I had found on a website) on my (working) validation script:

if (register.username.match(/\W/)) {
    alert('You have special characters on username field.');
    return false;
}

It did nothing, and it also prevented the whole script from working.

This is the html form (not the whole thing):

<form name="register" method="POST" action="registar.php" onsubmit="return validateForm();">
    <ul class="left-form">
        <h2>Nova conta:</h2>
        <li>
            <input type="text" name="username" placeholder="Username" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="text" name="email" placeholder="Email" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="password" name="pass" placeholder="Password" required/>
            <div class="clear"> </div>
        </li>
        <li>
            <input type="password" name="pass_confirm" placeholder="Confirmar a password" required/>
            <div class="clear"> </div>
        </li>
        <input type="submit" value="Registar">
        <div class="clear"> </div>
    </ul>
</form>

And this is my Javscript code (without the special characters checking):

function validateForm() {
    if (register.username.value.length <= 2) {
        alert("O username escolhido é demasiado curto.");
        return false;
    }
    if (register.username.value.length > 20) {
        alert("O username escolhido é demasiado longo.");
        return false;
    }
    var x = register.email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("O email inserido parece ser inválido.");
        return false;
    }
    if (register.username.value == register.pass.value) {
        alert("Por questões de segurança, pedimos que use uma password diferente do seu nome de utilizador.");
        return false;
    }
    if ((register.pass.value.length < 6) || (register.pass.value.length > 20)) {
        alert("Certifique-se que a sua password tem entre 6 e 20 letras.");
        return false;
    }
    if (register.pass.value != register.pass_confirm.value) {
        alert("As passwords não condizem.");
        return false;
    }
    return true;
}

Ignore the alerts as they are only the display messages.

Can someone write a piece of code which checks for special characters (! , . + * etc.) or tell me what's wrong with the code I used?


Solution

  • You probably should change the code to this:

    if (register.username.value.match(/\W/)) {
       alert('You have special characters on username field.');
       return false;
    }
    

    What's the difference? Well if you have realized I added .value in the middle. Because register.username would refer to the username input element and it doesn't have a match method. We need to check the text entered in it. By checking input element reference, you can realize we use it's value property which returns the text entered. So register.username.value is the text entered by the user and since it's a string we can use .match method on it.

    You can now pass any regex to the match method that would satify your needs. Check the guide on regex also.

    Also always check for errors shown in the developer console.