Unobtrusive Number Field Validation Using JavaScript

© copyright 25.Jun.2008 by Paul Bradley filed under JavaScript


[Ad] need a break from coding?

Hoseasons Villas

"Unobtrusive JavaScript" is an emerging technique used in the JavaScript programming community, which suggests best practices, including separating functionality from the web page's markup, and gracefully degrading in situations where older browsers can't handle the advanced JavaScript.

Adding onblur field validation - Example : Checking for numbers, within a telephone number field.

In this example, we will add validation to a telephone number field within a demographics form. While using JavaScript to give instant feedback to the users about any incorrectly formatted data entered into our forms is useful, we should not rely on JavaScript being present or supported, and should always validate data being submitted to the server, at the server end.

Consider the HTML code below, this is our basic demographics form code, with just one field having an id of telephone. As you can see there is no JavaScript code present, and this form would work for users who have JavaScript turned off. In this example our update.php script would also validate the telephone number when submitted to the server, accommodating our non-JavaScript visitors.


<form id="demographics" action="update.php" method="POST">

<label for="telephone" id="lbl_telephone">Telephone No:</label>
<input class="input" type="text" name="telephone" id="telephone" />


<input type="submit" value="update" />
</form>

Adding an onblur event to the telephone field

Now we have the basic form defined, we can use JavaScript to enhance it's functionality by attaching an onblur event to the telephone field. To do this we will use the window.onload event, as this fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading. However, we can't just assume that all the DOM elements we need are there, so it's good programming practice to check if the DOM element id's we need are actually present, and fail gracefully if they are not.

In the example JavaScript code shown below, we start by assigning a function reference prepare_form to the window.onload event; so that once the document has finished loading, the function prepare_form is executed.

This function does four things, it first checks to ensure the current DOM supports the getElementById function and fails gracefully if its not supported. It then uses the getElementById function to check for the presence of an element with the id of telephone. If it does not find one it fails gracefully, this is important as we can't assume the telephone field is always going to be there, designers might change the form in the future and break our code, so by implicitly checking for elements, we can ensure our code will continue to work with no adverse side affects. The code then assigns the element to a variable called telephone, so that we can then change it's onblur event to validate_number.

window.onload = prepare_form;

function prepare_form() {
    if(!document.getElementById) return false;
    if(!document.getElementById("telephone")) return false;

    var telephone = document.getElementById("telephone");
    telephone.onblur = validate_number;
}

After the prepare_form function has executed, our telephone field has an onblur event which will be triggered when the user tabs out of that field. Next we will look at using JavaScript regular expressions to validate that only numbers have been entered into the field.

Using JavaScript Regular Expressions for Number Validation

When writing the validate number function, we first of all check that the element with am id of telephone is present, and exit gracefully if not. We then assign the element to a variable called telephone, and search the contents of the fields current value, using the regular expression /^[0-9]*$/, to ensure only numbers between 0 and 9 are used in the field.

If the field value contains characters other than the numbers zero through nine, then we use the alert function to pop-up an error message in a dialog, and return the cursor focus to the telephone field.

function validate_number() {
    if(!document.getElementById("telephone")) return false;

    var telephone = document.getElementById("telephone");

    if(telephone.value.search(/^[0-9]*$/) == -1) {
        alert('Telephone field contains invalid
' +
              'characters please correct.');
        telephone.focus();
        return false;
    } else {
        return true;
    }
}

But I need to validate numbers, spaces and brackets

It's quite possible you will need other characters beside just numbers to validate telephone numbers, for example you may need to accept spaces or brackets to allow dialling prefixes to be shown differently, i.e. (07092) 392 745

In this case the regular expression needs to be extended to :

if(telephone.value.search(/^[0-9] ()*$/) == -1)

 


If you have found this article helpful or useful please consider linking to it, emailing it to friends, or share it with others using social sites like del.icio.us, Stumble Upon or Twitter.

Paul Bradley

About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He provides PHP & MySQL bespoke development services via his software development company, Carlisle Software Limited.
He has over 20 years programming experience.

Other Popular Articles

Categories & Topics

Home · Apache · JavaScript · Perl · PDF · PHP · MySQL · MSSQL · TAR · Ubuntu Linux · Video · Visual Basic

Browse the complete article history, and if you like what you see; consider subscribing to the rss feed.