Form Validation on the Client Side

    Martin Tsachev
    Share

    Forms validation on the client-side is essential — it saves time and bandwidth, and gives you more options to point out to the user where they’ve gone wrong in filling out the form. Having said that, I don’t mean that you don’t need server-side validation. People who visit your site may use an old browser or have JavaScript disabled, which will break client-only validation. Client and server-side validation complement each other, and as such, they really shouldn’t be used independently.

    Why is Client Side Validation Good?

    There are two good reasons to use client-side validation:

    1. It’s a fast form of validation: if something’s wrong, the alarm is triggered upon submission of the form.
    2. You can safely display only one error at a time and focus on the wrong field, to help ensure that the user correctly fills in all the details you need.
    Two Major Validation Approaches

    The two key approaches to client-side form validation are:

    • Display the errors one by one, focusing on the offending field
    • Display all errors simultaneously, server-side validation style

    While displaying all errors simultaneously is required for server-side validation, the better method for validation on the client-side is to show one error at a time. This makes it possible to highlight only the field that has been incorrectly completed, which in turn makes revising and successfully submitting the form much easier for the visitor. If you present users with all errors at the same time, most people will try to remember and correct them at once, instead of attempting to re-submit after each correction.

    Given these advantages, I’ll focus only on validation methods that display one error at a time.

    How to Validate Forms

    Take for example the following code fragment:

    <script type="text/javascript" language="javascript"> 
    function validateMyForm() {
    if (parseInt(document.forms[0].phone.value)  
           != document.forms[0].phone.value) {
    alert('Please enter a phone number, numbers only');
    return false;
    }

    return true;
    }
    </script>

    <form action="handler" onsubmit="return validateMyForm();">
    <p>Phone: <input type="text" id="phone" name="phone" /></p>

    <p><input type="submit" value="Send" /></p>
    </form>

    What’s wrong here? Well, if you add another form before this one, the code will try to validate the wrong form.

    A better approach would be to include a form name:

    function validateMyForm() { 
    if (parseInt(document.forms.myForm.phone.value)  
           != document.forms.myForm.phone.value) {

    <form id="myForm" name="myForm" action="handler"  
    onsubmit="return validateMyForm();">

    This is definitely better, but still not portable enough — if you want to reuse some of this validation on another form, you’ll have to do a lot of text replacing first.

    So let’s remove the form name:

    function validateMyForm(form) { 
    if (parseInt(form.phone.value) != form.phone.value) {

    <form action="handler" onsubmit="return validateMyForm(this);">

    This last method makes use of the object this, which always points to the current object. This makes our code more portable, and saves typing.

    Now how about making visitors’ lives a lot easier? Let’s focus on the field that triggered the error, instead of making them find it on their own.

    function validateMyForm(form) { 
    if (parseInt(form.phone.value) != form.phone.value) {
    alert('Please enter a phone number, numbers only');
    form.phone.focus();
    form.phone.select();
    return false;
    }

    With these changes, the browser will focus on the incorrectly filled out field, and even select the text for the visitor. If scrolling is needed, this will also happen automatically.

    Ok, that was pretty good, but don’t you feel that it’s a little too much code for every field? What if we create a simple library of functions that can save lots of typing and download time for the page? Well, next we’ll do exactly this — and we’ll define our basic functions, to make the validation code even shorter.

    function validateNumber(field, msg, min, max) {  
    if (!min) { min = 0 }  
    if (!max) { max = 255 }  
     
    if ( (parseInt(field.value) != field.value) ||  
           field.value.length < min || field.value.length > max) {  
    alert(msg);  
    field.focus();  
    field.select();  
    return false;  
    }  
     
    return true;  
    }

    This function performs the simple validation of a number — it checks whether the field contains digits only, and optionally, if it is within a given range. You’ll note that this code passes the error message as a parameter. To use such a function, we can basically add it to the onsubmit handler, like so:

    <form action="handler"  
    onsubmit="return validateNumber(this.phone,  
    'Please enter a phone number, numbers only', 5, 10);">

    Called like this, it will check whether the phone number is numeric, and is more than 5, but less than 10 digits long. Note how the phone object is passed as a parameter? This allows us to focus upon it via the helper function, as opposed to passing the value of the field only.

    Another method for validating numbers is to require them to be within a given range. To make the function do this kind of validation, simply change the check line to:

    if ((parseInt(field.value) != field.value) ||   
    field.value < min || field.value > max) {

    If you want to apply more than one check to the form, you can embed several rules in the onsubmit handler. Imagine, for example, that we require first and last name to be entered, in addition to the phone number:

    <form action="handler"  
    onsubmit="return (  
    validateNumber(this.phone, 'Please enter a phone  
           number, numbers only', 5, 10) &&  
    validateString(this.firstName, 'Please  
           enter your first name', 3, 15) &&  
    validateString(this.lastName, 'Please  
           enter your last name', 3, 15)  
    );">

    The code requires all validation rules to evaluate to true (with the logical AND - &&). A closer look reveals that it’s very easy to generate this kind of code from a server scripting language… but that’s a whole other article.

    function validateString(field, msg, min, max) {  
    if (!min) { min = 1 }  
    if (!max) { max = 65535 }  
     
    if (!field.value || field.value.length < min ||  
    field.value.max > max) {  
    alert(msg);  
    field.focus();  
    field.select();  
    return false;  
    }  
     
    return true;  
    }

    As you can see, the string validation function looks more or less the same; you can also write other functions and combine them with these.

    A common field required in many forms on the Web is the user’s email address. I’ve seen a lot of functions to do this, but usually the simplest and easiest way to validate an email address is to use regular expressions.

    Now we’ll extend our function, making it possible to define the field as optional.

    function validateEmail(email, msg, optional) {  
    if (!email.value && optional) {  
    return true;  
    }  
     
    var re_mail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+  
           ([a-zA-Z])+$/;  
    if (!re_mail.test(email.value)) {  
    alert(msg);  
    email.focus();  
    email.select();  
    return false;  
    }  
     
    return true;  
    }

    To validate a required email you should call it as:

    validateEmail(this.email, 'Please enter your email address')

    and if you want it to be optional:

    validateEmail(this.email, 'Please enter a correct   
    email address or leave the field blank', true)

    JavaScript cannot be used on its own for validation, but it helps a lot if you have it. The more compact the code you embed into your HTML, the better — it saves download time, and search engines will like you for it!