JavaScript

JavaScript Form Validation Example

EDITORIAL NOTE: In this post, we feature a comprehensive JavaScript Form Validation Example. Validation is the process of ensuring that user input is clean, correct, and useful.

If you’re looking to build an interactive website, which contains any form of input, then you should validate the data you get from the users.

If it’s a registration form you have to validate the name and surname fields, the e-mail, username, age, zip code and everything else, so that you don’t send unnecessary calls to your server. Below you’ll find out how you can do that using JavaScript.

What are we validating?

Let’s start with building a registration form with multiple input fields, so that we can have something more concrete to work on. Create an HTML file named index.html and write this code in it:

<!DOCTYPE html>
<html>
<head>
    <title>Validation</title>
    <script src="validation.js"></script>
</head>
<body onload="document.registration.userid.focus();">

<h1>Registration Form</h1>
<form name='registration' onSubmit="return formValidation();">
    <ul>
        <li>
            <label for="userid">User id:</label>
            <input type="text" name="userid" size="12" />
        </li>

        <li>
            <label for="passid">Password:</label>
            <input type="password" name="passid" size="12" />
        </li>

        <li>
            <label for="username">Name:</label>
            <input type="text" name="username" size="50" />
        </li>

        <li>
            <label for="address">Address:</label>
            <input type="text" name="address" size="50" />
        </li>

        <li>
            <label for="country">Country:</label>
            <select name="country">
                <option selected="" value="Default">(Please select a country)</option>
                <option value="AF">Afghanistan</option>
                <option value="AL">Albania</option>
                <option value="ALG">Algeria</option>
                <option value="AND">Andorra</option>
                <option value="ANG">Angola</option>
            </select>
        </li>

        <li>
            <label for="zip">ZIP Code:</label>
            <input type="text" name="zip" />
        </li>

        <li>
            <label for="email">Email:</label>
            <input type="text" name="email" size="50" />
        </li>

        <li>
            <label id="gender">Sex:</label>
            <input type="radio" name="sex" value="Male" />
            <span>Male</span>
            <input type="radio" name="sex" value="Female" />
            <span>Female</span>
        </li>

        <li>
            <label>Language:</label>


                <input type="checkbox" name="en" value="en" checked />
                <span>English</span>


                <input type="checkbox" name="nonen" value="nonen" />
                <span>Non English</span>

        </li>

        <li><input type="submit" name="submit" value="Submit" /></li>
    </ul>
</form>
</body>
</html>

This is the whole HTML code for the registration form. We haven’t made it look pretty, since we’re only going to use it for demonstration purposes. We have assigned it the name “Registration Form”, and then have put the following labels and input fields in an unordered list: user id, password, name, address, zip code, e-mail and about. Also we have included two checklists, respectively labeled as sex and language. Moreover, we have included a dropdown for countries (we only listed the first five, not the complete list of countries) and a submit button. Now we can go on and validate the information we get from these inputs.

Validation functions

Now that we have a registration form from which to get the information, we can start working on the validation functions. First of all, we create a JavaScript file named validation.js (or anything you want, but then you would have to change the name when scripting it).

User Id validation
The first field to validate is the user id. Take a look at the function:

function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a username.\n";
        alert(error);
        return false;

    } else if ((fld.value.length < 5) || (fld.value.length > 12)) {
        fld.style.background = 'Yellow';
        error = "The username is the wrong length.\n";
        alert(error);
        return false;

    } else if (illegalChars.test(fld.value)) {
        fld.style.background = 'Yellow';
        error = "The username contains illegal characters.\n";
        alert(error);
        return false;

    } else {
        fld.style.background = 'White';
    }
    return true;
}

By using this function, we require the user to not leave the input field blank, and that his/her username only contains letters, numbers and underscores, but not forward slash or backslash. The function puts out an alert if the field is left empty, the username length is less than 5 or more than 12 and also if the username contains illegal characters.

Password validation
Passwords are another form of input that requires validation. Check the code below:

function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers
 
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
        alert(error);
        return false;
 
    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
        error = "The password is the wrong length. \n";
        fld.style.background = 'Yellow';
        alert(error);
        return false;
 
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = 'Yellow';
        alert(error);
        return false;
 
    } else if ( (fld.value.search(/[a-zA-Z]+/)==-1) || (fld.value.search(/[0-9]+/)==-1) ) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
        alert(error);
        return false;
 
    } else {
        fld.style.background = 'White';
    }
   return true;
}

Again, we only allow letters and numbers (but no underscores this time around) and we put out an alert if the field is left empty, if it contains illegal characters, or if it does not contain at least one number.

Name validation
To validate the users name, write this code:

function allLetter(uname)
{
    var letters = /^[A-Za-z]+$/;
    if(uname.value.match(letters))
    {
        return true;
    }
    else
    {
        alert('Username must have alphabet characters only');
        return false;
    }
}

This function returns true if the name is composed by letters and whitespaces only, and puts out an alert if not.

Address validation
We validate the users address like this:

function alphanumeric(uadd)
{
    var letters = /^[0-9a-zA-Z]+$/;
    if(uadd.value.match(letters))
    {
        return true;
    }
    else
    {
        alert('User address must have alphanumeric characters only');
        return false;
    }
}

By using this code snippet we put out an alert if the address does not include alphanumeric characters only.

Country Validation
Since you have given the users a list of countries to use from, the condition for validation is just choosing a country from that list. The code would be this:

function countryselect(ucountry)
{
    if(ucountry.value == "Default")
    {
        alert('Select your country from the list');
        return false;
    }
    else
    {
        return true;
    }
}

If the users just leaves the default one as a value, an alert would be presented to him/her.

ZIP code validation
The ZIP code should be numbers only, so with the following function we put out an alert that says “ZIP code should have numeric characters only”:

function allnumeric(uzip)
{
    var numbers = /^[0-9]+$/;
    if(uzip.value.match(numbers))
    {
        return true;
    }
    else
    {
        alert('ZIP code must have numeric characters only');
        return false;
    }
}

Email validation
Email is one of the most used input fields in forms, together with username and password fields. It is also one of those that most need a validation function, which should look something like this:

function checkEmail() {

    var email = document.getElementById('txtEmail');
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value)) {
    alert('Please provide a valid email address');
    email.focus;
    return false;
 }
}

This function checks if the string which should be an email contains characters in uppercase, lowercase and numbers in it’s first part, then an”@” sign, then again lowercase, uppercase or number, then a dot, and finally 2 to 4 characters again in uppercase, lowercase or numbers. If this is not the structure of the string, it puts out an alert, saying that the email is invalid.

Gender validation
The input for gender is in the form as radio buttons, which should be clicked. The validation function will look like below:

function validgender(mgender,fgender)
{
    x=0;

    if(mgender.checked)
    {
        x++;
    } if(fgender.checked)
{
    x++;
}
    if(x==0)
    {
        alert('Select Male/Female');
        return false;
    }
    else
    {
        alert('Form Successfully Submitted');
        window.location.reload()
        return true;}
}

This function only makes sure that one of the options is checked, else it puts out an alert asking the user to check the button. The same function only with different variables is used to validate the language.

The mother validator

All these functions we wrote should be concluded in a single validation function that will be called on onSubmit. This function would be like so:

function formValidation()
{
    var uid = document.registration.userid;
    var passid = document.registration.passid;
    var uname = document.registration.username;
    var uadd = document.registration.address;
    var ucountry = document.registration.country;
    var uzip = document.registration.zip;
    var uemail = document.registration.email;
    var mgender = document.registration.msex;
    var fgender = document.registration.fsex; 
    
    if(validateUsername(uid,5,12))
    {
        if(validatePassword(passid,7,12))
        {
            if(allLetter(uname))
            {
                if(alphanumeric(uadd))
                {
                    if(countryselect(ucountry))
                    {
                        if(allnumeric(uzip))
                        {
                            if(ValidateEmail(uemail))
                            {
                                if(validgender(mgender,fgender))
                                {
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return false;
}

Note that this main validator called formValidator is executed as soon as the submit button is clicked.

And that’s about it.

Download the source code

This was an example of form validation using JavaScript.

Download
You can download the full source code of this example here: FormValidation

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
amit
amit
9 years ago

Suggesting some improvements. 1: Assign classes to error and success fields instead of directly assigning colors. 2: Never use alerts. If there are 10 fields and the user clicks the submit button by mistake, the user will have to click “OK” to 10 alert boxes. Instead show an message just below the input. 3: You are passing the input filed tn the validation method, pass a filed for error as well and set the field’s inner HTML as the error message. 4: The error checking methods should be independent of the way they are going to be used. The “validgender”… Read more »

jennerousity
jennerousity
8 years ago
Reply to  amit

amit

I’m sorry I am super new at this. Couls you show examples of your suggestions in code so I have a visual reference to what you are saying. I get what your saying I’m just not sure exactly how to write it.

imran
9 years ago

i want this for my website

Dominic Ancelm
Dominic Ancelm
7 years ago

As Amit suggested, the alert message should be below each field, to indicate the errors.
Then it would be a great validation form

Back to top button