Home » JavaScript » JavaScript Form Validation Example

About Era Balliu

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.

JavaScript Form Validation Example

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.

JavaScript Interview Coming Up?

Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!

In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!

 

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

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

3 comments

  1. 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” method is implementation specific and require you to always use it as the last validator.
    5: There is 8 levels of “if(){}” nesting in the formValidation() method. Instead call each one after another and return false if any one fails.

    I think you also pasted the code of your old email validation function “checkEmail()” instead of “ValidateEmail(uemail)”

    P.S. I don’t intend to offend you. This is really good effort on your part sharing your knowledge, and that what i too am trying to do. This will definitely help Javascript new comers on writing their own validators.

    • 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook