How to validate forms with JavaScript

Discover why and how you should use unobtrusive JavaScript to validate forms.

Introduction

Server side validation is the only way to reliably validate forms. Using client-side JavaScript exclusively should be avoided for the following reasons:

A device may not have JavaScript available

A user might have turned JavaScript off

An administrator might have disabled JavaScript on a network

As well as making sure that all your forms are validated on the server, you can also use JavaScript to validate forms. Validating a form twice is not a waste of time as we can use JavaScript to unobtrusively enhance the usability of the form. The unobtrusive JavaScript will stop the form submission if JavaScript is available and speed up the form submission process. As JavaScript is client side, users won't have to wait for the page to reload if errors have been made submitting the form (this is particularly useful to users with slow connections).

The fields are labeled as being required by inserting an image within the <label> tag with alt="required".

onsubmit for testing

Initially we'll also insert an onsubmit with a call to our form validation script. This will help us test the page as the JavaScript develops. It'll be removed at the end of this article and a function call will be assigned to the form itself with JavaScript.

We'll insert the HTML extra code as follows:

<formonSubmit="validateForms()"action="#">

The JavaScript

We'll create a JavaScript file and call it js.js. The function we've called on the onsubmit command is called validateForms(), so we start by creating that empty function at the start of the js.js file:

function validateForms()
{
}

The validateForms() function is the root function that will be used to control how the form is validated. The validation script will then be applied to all forms. Let's start by getting an HTML object collection of any form on the HTML page:

Looping

The next step in the validation process is to loop through the forms and validate them. All forms will be handled in the same way. We'll do this using a for loop to loop through the HTML object collection, with each form being passed to a new function called validateForm():

Task order

At this point, it's probably useful to stop and think about how we might implement the JavaScript validation. If we return to the form HTML, you will, of course, have noticed that we've applied a class to each of the required <input>s:

The e-mail <input> has class="reqemail" assigned to it and the question <input> has class="reqquestion". These will be used to identify the <input>s to the JavaScript as requiring validation and defining what type of validation they require. We can now use getElementsByTagName to access the class definitions on each of the inputs. When we use the getElementsByTagName at the start of the article to create a collection of forms, we use the entire document as its parent.

elementsForms = document.getElementsByTagName("form");

We can also get all <input>s contained by the form that we've passed to the validateForm(currentForm) function:

validateEmail(elementsInputs, intCounter) will return true if the e-mail address isn't valid. In the above example, this triggers an alert in the validateForm(currentForm) function. We'll check to see if the 'How useful did you find this article?' <input> has any text entered:

Separating HTML, JavaScript, and CSS

The final task is to remove all JavaScript from the HTML page. The onsubmit function we applied to the <form> at the start of the article can now be removed and we can apply the function call validateForms() to all forms. The opening <form> tag should now read as follows:

<formaction="#">

We should now apply the form onsubmit function call to all form tags within the .js file.