/ javascript

JavaScript - Object Oriented Form Validation

This tutorial aims to teach you a better way to validate your forms that doesn't rely on naming your forms, or worse, relying heavily on IDs. Wherever possible, ID usage should be removed.

Why Bother?

By not having to use IDs or naming our forms:

  • we do not have to worry about ensuring that our IDs are unique across any other content that might be shown on the same page.
    • In today's world of development tens or hundreds of "partials" may mixed and matched in any number of ways to build a page with the combination likely to change by user interaction or general updates to the site.
  • we can use prototyping to generate hundreds of forms on the page which are slightly different to each other in their pre-populated values, but all use the same validation method.

Steps

First of all your form should implement an onsubmit method which will call our validation function. The key thing is to pass this to the validation method as shown below:

<form onsubmit="return validate_form(this);" ... >

Now we can define our validation method with the form element as our first parameter. We will use this and nothing else for checking the values/inputs. For example:

function validate_form(formElement)
{
    var passedValidation = false;
    var inputElementValue = formElement['input1'].value;
    
    if (inputElementValue === "hello world")
    {
        passedValidation = true;
        alert('validation passed');
    }
    else
    {
        alert('invalid value');
    }
    
    return passedValidation;
}

For this example, the form had a text input with a name of input1 and the form would only submit if the value was "Hello World".

A full demonstration of this can be found below:

<html>
<body>

<form method="post" action="" onsubmit="return validate_form(this)">
    <input type="text" name="input1" />
    <input type="submit" />
</form>


<form method="post" action="" onsubmit="return validate_form(this)">
    <input type="text" name="input1" value="hello world" />
    <input type="submit" />
</form>


<script>
function validate_form(formElement)
{
    var passedValidation = false;
    var inputElementValue = formElement['input1'].value;
    
    if (inputElementValue === "hello world")
    {
        passedValidation = true;
        alert('validation passed');
    }
    else
    {
        alert('invalid value');
    }
    
    return passedValidation;
}
</script>

</body>
</html>

Stuart Page

Stuart Page

Stuart is a software developer with a passion for Linux and open source projects.

Read More