Pin Me

Using JavaScript to Validate Forms

written by: S. R. Obbayi•edited by: Amy Carson•updated: 7/30/2011

There is nothing as stressful for the web developer as having some user abuse your HTML web forms. The sad truth is that this kind of abuse will never end. JavaScript form validation offers some elegant solutions to this, here's how.

  • slide 1 of 9

    JavaScript in a Nutshell

    JavaScript is a powerful and popular scripting language out of the ECMA Script family of scripting languages. JavaScript is ideal for bringing life to static web pages as well as improving the user experience on websites. It is also great for making discreet requests to and from the web server also known as Ajax and JSON.

    One thing that we will focus on now is JavaScript's ability to do web forms validation.

  • slide 2 of 9

    What Should I Validate?

    With JavaScript you can validate practically every possible element that can appear on a web form. It is all up to you to decide what you want to ensure is entered correctly by your users. Some elements do need to validated at all times. These include email fields, URL fields, name fields, password fields and fields expecting phone numbers.

    The reason why these must be validated is not so much the abuse but to simply ensure that the user does not make careless mistakes or simple typing errors.

  • slide 3 of 9

    Validation Foundation

    There are dozens of methods you can choose to validate your forms using JavaScript. Every developer would normally write his code one way while another would write his own code in a different way. Whichever way you choose does not matter. What is important is that your code is well formed and works.

    Below I have a block of code that will work with both old and new browsers and is simple enough to use.

    Take a form with the following header <form name="myform" onSubmit="return validate()">.

    This header gives the form an identifying name and an instruction to call a validation function when the form is submitted.

    The base function which will be called should be placed in the HTML header section and would look like this:

    function validate(){

    with document.myform{

    //your validation tests come here


    return true;


    The form above simply ensures we are dealing with an element named “myform" in this case a web form, and if all tests pass it returns true. This means it allows the form to be submitted.

    Let us now look at a few tests. Please note that all tests are placed in the marked section of the code above.

  • slide 4 of 9

    Checking for Numeric Characters

    JavaScript phone validation When you ask a user for a telephone number you expect a few things. That the telephone number is 10 digits long for those in USA and all characters must be numerical digits. There is more we can test for but this will do for demonstration purposes.

    So how can we write a test for this assuming our telephone text field in named “phone"? We can use a test that looks like this.

    var numberfilter = /D/;

    var returnval = numberfilter.test(phone.value);

    if( phone.value == '' || returnval == false || phone.value.length != 10){

    alert("Please type in a valid phone number.");


    return false;


    What the code does here, is, it creates a test for digits and runs the test against the value entered in the phone field keeping the result.This test is based on a regular expression which, formated in the way it is, the Capital "D" tells the code to look for numeric digits and no other form of characters.

    Next it checks is the phone field is blank, or if the number of characters is not equal to 10. If any of these tests fail, JavaScript will pass a message to the user asking them to put in a valid phone number. It then puts the cursor in the phone field and returns false; basically it aborts sending the form. If these tests pass then it simple moves on to the next field's test.

  • slide 5 of 9

    Preventing Empty Fields

    Preventing empty fields is just as the test above but with less complexity. Looking at this example for a field called “lastname".

    if(lastname.value == ''){

    alert("Please type in your Surname Name.");


    return false;


    Here you can see the structure and flow is similar to the test for the telephone number. Al this does is to make sure the “lastname" field is not blank. The rest is the same as the numerical field.

  • slide 6 of 9

    Simple Password Checks

    JavaScripr password validation Checking for passwords can follow a slightly different rule. You can check the length of a password using the same rule for the phone number. Without having to repeat, you can check that the password entered into a “password" filed matches the “confirm _password" field

    if(password && password.value == ''){

    alert("Please type in a password.");


    return false;


    if(confirm_password && confirm_password.value != password.value){

    alert("Your passwords do not match, please correct.");


    confirm_password.value = '';

    return false;


    This test requires a few additional fields. This test first checks that there is a “password" field and it is not blank. If this test fails the user is asked to type in a password. If the user did type in a password the test moves onto the second part of the test which checks that there is a “confirm_password" field and the value in that field is similar to the content in the password field. If this test fails it deletes everything in the “password" field and the user has to type in both passwords a fresh.

    The reason why we delete the information in the “password" field is because it is masked and there may have been a typing error.

  • slide 7 of 9

    Well Formed Emails

    JavaScript Email Validation Validating emails and URLs follows similar rules to those of checking for numerical digits. The main difference is that the “email" field uses a more complex regular expression as seen below. The rest of the code follows the same path as all the others above

    var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,5}|\d+)$/i;

    var returnval = emailfilter.test(email.value) ;

    if(email.value == '' || returnval == false){

    alert("Please type in a valid email address.");


    return false;


    The regular expression looks for combinations of any number of alphanumeric characters with any number of “dots" and a single “@" sign and any number of alphanumeric characters after the “@" sign. Finally it checks for an extension between two and five characters in length.

  • slide 8 of 9

    These are the most common fields that require validation when designing web forms. The important thing to note is that form validations are totally up to the website owner. The general rule is that anything can be validated. Whatever you choose to validate you will probably be using one of the tests listed above in form or slightly modified.

    With a little bit of hands-on practice JavaSript form validation will become second nature to the web developer.

  • slide 9 of 9



    • JavaScript Documentation,
    • Standard ECMA-262 Documentation,
    • Screen shots provicded by Writer