Wednesday, September 18, 2024

HTML Forms Validation on the Client Side

Form validation on the client-side is essential – it saves time and bandwidth; you also have better control to show the user the wrong field. This comparison of different validation methods includes comments for improving portability and maintainability.

Why is Client Side Validation Good

  • It is fast, if something is wrong the alarm is triggered upon submission of the form
  • You can safely display only one error at a time and focus on the wrong field
  • Two Major Validation Approaches

  • Display the errors one by one, focusing on the offending field
  • Display all errors, server-side validation style
  • While displaying all errors is needed in case of server validation, the better method for client validation is to show one error at a time. This makes it possible to highlight the wrong field, making it a lot easier for the visitor. If you print all errors most people would also try to remember and correct them at once instead of trying to submit after each correction.

    Considering these advantages I will 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() {
    &nbsp&nbsp&nbsp&nbsp if (parseInt(document.forms[0].phone.value) !=
    &nbsp&nbsp&nbsp document.forms[0].phone.value) {
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp alert('Please enter a phone number, numbers only');
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp return false;
    &nbsp&nbsp&nbsp&nbsp }

    &nbsp&nbsp&nbsp&nbsp return true;
    }
    </script>

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

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

    So what’s wrong: If you add another form before this one the code will try to validate the wrong one.

    Note: JavaScript is case sensitive, the value which is assigned to the HTML id/name attribute is also case sensitive.

    A better approach would be to add a form name:

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

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

    This is definitely better but still not portable enough – if you want to reuse some of the validation for another form you will have to do a lot of text replacing.

    Let’s remove the form name:

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

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

    The last method makes use of the this object which always points to the current object, making our code more portable and saving keystrokes.

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

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

    With these changes the browser will focus the wrong field and even select the text for the visitor, if scrolling is needed it will also happen automatically.

    That was pretty good, but don’t you feel that it’s a little too much code for every single field? If we create a simple library of functions we can save lots of typing and download time for the page.

    Well next we’ll do exactly this and define our basic functions that make validation code even shorter.

    function validateNumber(field, msg, min, max) {
    &nbsp&nbsp&nbsp&nbsp if (!min) { min = 0 }
    &nbsp&nbsp&nbsp&nbsp if (!max) { max = 255 }

    &nbsp&nbsp&nbsp&nbsp if ( (parseInt(field.value) != field.value) ||
    &nbsp&nbsp field.value.length max) {
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp alert(msg);
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp field.focus();
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp field.select();
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp return false;
    &nbsp&nbsp&nbsp&nbsp }

    &nbsp&nbsp&nbsp&nbsp return true;
    }
    This function does a simple validation of a number – it checks whether the field contains digits only, and optionally if it is within a given range.

    We are passing the error message as a parameter to it, to use such a function we can basicly add it to the onsubmit handler like:

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

    So called it will check if the phone is numeric, it is more than 5 digits and less than 10. Note how the phone object is passed as a parameter, this allows us to focus 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 in a given range, to make the function do this kind of checks simply change the check line to:

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

    If you want to apply more than one checks to the form you can embed several rules in the onsubmit handler, imagine that we also require first and last name to be entered:

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

    The code requires all validation rules to evaluate to true (with the logical AND – &&). A closer look reveals the fact that it is very easy to generate such code from a server scripting language, but that’s a whole another article.

    function validateString(field, msg, min, max) {
    &nbsp&nbsp &nbsp&nbsp if (!min) { min = 1 }
    &nbsp&nbsp &nbsp&nbsp if (!max) { max = 65535 }

    &nbsp&nbsp &nbsp&nbsp if (!field.value || field.value.length max) {
    &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp alert(msg);
    &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp field.focus();
    &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp field.select();
    &nbsp&nbsp &nbsp&nbsp &nbsp&nbsp return false;
    &nbsp&nbsp &nbsp&nbsp }

    &nbsp&nbsp &nbsp&nbsp 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 too.

    A common field required in many forms on the web is the email, there’re lots of functions I’ve seen but usually the simplest and easiest way to validate an email is using regular expressions.

    We’ll extend the function, making it possible to define the field as optional.

    function validateEmail(email, msg, optional) {
    &nbsp&nbsp&nbsp&nbsp if (!email.value && optional) {
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp return true;
    &nbsp&nbsp&nbsp&nbsp }

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

    &nbsp&nbsp&nbsp&nbsp 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 code you embed in your HTML, the better – it saves download time and search engines will like you.

    Martin Tsachev has been developing for the web since 2001. He’s currently working as
    a web developer at Make-a-Store, Inc.. Martin’s
    personal site mtWeb can be found at martin.f2o.org.

    Related Articles

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    Latest Articles