# VBForums CodeBank > CodeBank - JavaScript >  [Javascript OOP] - Easy Form Validation

## the182guy

Introduction
This is an Object Oriented Javascript form validation framework. I created this because I have written countless forms which require client side validation, each time I did a form I found myself copy and pasting a simple Javascript into the page to do basic form validation.

I designed this component to be very easy to use, easy to add to existing forms and require very little code from the programmer. Whilst creating this I also had the W3C web standards in mind, so you will find that it will not cause your page to fail a W3C validation test.

Below I will explain everything about the Validator, but be sure to download the *samples attached* which you can play around with.

Simple Usage
To use the basic functionality all you have to do is include the classes in the page you want to use it on. All the classes are inside the easy_validation.js file.


javascript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Easy Form Validation</title> <script type="text/javascript" src="easy_validation.js"></script><script type="text/javascript">        function validate()    {        var v = new Validator(); //create a new Validator object called v                //setup the fields we want to validate                //          NAME                VALIDATION      ELEMENT ID        v.addField("Your Number",       "NUMBER",       "my_number");        v.addField("Your Date",         "DATE",         "dob");        v.addField("Your Text",         "NOT_EMPTY",    "line1");        v.addField("Email address",     "EMAIL",        "email");        v.addField("Terms",                       "CHECKBOX",       "terms");                //call the validateForm method and return the result to the form element        return v.validateForm();    }    </script> </head> <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;"> <h1>Simple Usage</h1> <form name="contact_us" method="post" action="simple_example.html" onsubmit="return validate();" />Enter a number: <input type="text" id="my_number" value="89" /><br />Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />Enter some text: <input type="text" id="line1" value="abcdefg" /><br />Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />Do you accept our terms? <input type="checkbox" id="terms" /> <input type="submit" name="submit_button" /></form> </body></html>


The example above will produce a popup with the list of validation errors (if any). The only special things about the form are that each element has  ID which is needed for the Validator to pickup the field, *and the onsubmit event of the form element*. That event tells the form to call our validator function when submitted, if it fails the validation tests, the form will not be submitted.

We create a function called validate in the head section of the page, which is where we set the parameters for the Validator object.
The addField method is self explanatory, however I will explain each of the arguments:

addField(NAME,  VALIDATION_TYPE,  ID,  CUSTOM_ERROR_MESSAGE)

NAME – This can be anything, it is only used when showing the default error message. This is not the actual name property of the element.ID - The element ID of the field to validateCUSTOM_ERROR_MESSAGE - This is optional, if set it will override the default error messageVALIDATION_TYPE – tells the Validator what validation to do on that field.

*Current list of validation types supported*
NUMBER – data must be numeric (can be decimal/float).DATE – data must be a date in format dd/mm/yyyy.BASIC – data must be at least three characters long.NOT_EMPTY – data must exist, can not be blank.EMAIL – data must appear to be a valid email address.NAME – data must only cantain alphabetic characters, no numbers or symbols.CHECKBOX – used on a checkbox/tickbox field, the checkbox must be ticked.

You can also change the default error message for all fields by using the setDefaultErrorMsg(“ERROR MESSAGE HERE”) method.

----------


## the182guy

Advanced Usage
I call this section Advanced Usage, but it is still very easy to use, the functionality that we make use of in this section is just more advanced.

You can show the error messages on the actual web page. I recommend doing this because it looks a lot more professional than just a popup.

To show the errors on your page, you just need to tell the Validator object to enable errors on the page, and also tell it which Div on your page to place the error HTML in.


javascript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Easy Form Validation</title> <script type="text/javascript" src="easy_validation.js"></script><script type="text/javascript">        function validate()    {        var v = new Validator(); //create a new Validator object called v                //tell the validator to display the errors on the page        v.setOutputType("DIV");        //tell the validator which Div to show the errors in        v.setOutputDivId("validation_errors");                //setup the fields we want to validate                //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE        v.addField("Your Name",         "NAME",         "my_name");        v.addField("Your Number",       "NUMBER",       "my_number");        v.addField("Your Date",         "DATE",         "dob");        v.addField("Your Text",         "NOT_EMPTY",    "line1");        v.addField("Email address",     "EMAIL",        "email");        v.addField("Terms",             "CHECKBOX",     "terms",        "You must accept our terms!!");                //call the validateForm method and return the result to the form element        return v.validateForm();    }    </script> </head> <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;"> <h1>Advanced Usage</h1> <p>This example will output the errors on the page.</p> <div id="validation_errors"></div> <form name="contact_us" method="post" action="advanced_example.html" onsubmit="return validate();" />Enter your Name: <input type="text" id="my_name" value="Chris" /><br />Enter a number: <input type="text" id="my_number" value="89" /><br />Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />Enter some text: <input type="text" id="line1" value="abcdefg" /><br />Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />Do you accept our terms? <input type="checkbox" id="terms" /> <input type="submit" name="submit_button" /></form> </body></html>


Notice in the above example we call setOutputType() and pass in “DIV”. There are three possible values for this argument which are ALERT – show errors in a popup, DIV – show errors in a div on the page and “BOTH” to show the errors in an alert and a div.

Also notice that when using a Div to display the errors, you must tell the Validator which div to use, by passing in the ID.

----------


## the182guy

More Advanced Features
In the above section I explained about displaying the errors on the page, which is great but what if you want to customise the way the errors are displayed on the page? You can create your own error template and have the errors displayed exactly how you want. Here’s an example


javascript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Easy Form Validation</title> <script type="text/javascript" src="easy_validation.js"></script><script type="text/javascript">        function validate()    {        var v = new Validator(); //create a new Validator object called v                //tell the validator to display the errors on the page        v.setOutputType("DIV");        //tell the validator which Div to show the errors in        v.setOutputDivId("validation_errors");                var t = new ErrorTemplate(); //create a new template object        t.setHeader ("<h2 style='color:red;'>Oops! Some errors occured!!</h2>");        t.setItem   ("<img src='x.gif' alt='error' /> {ERROR_MESSAGE}<br />"); //this line will be reprated with each error        t.setFooter ("<br />Please correct these errors.");                v.setErrorTemplate(t); //assign the new template object to the Validator for use                //setup the fields we want to validate                //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE        v.addField("Your Name",         "NAME",         "my_name");        v.addField("Your Number",       "NUMBER",       "my_number");        v.addField("Your Date",         "DATE",         "dob");        v.addField("Your Text",         "NOT_EMPTY",    "line1");        v.addField("Email address",     "EMAIL",        "email");        v.addField("Terms",             "CHECKBOX",     "terms",        "You must accept our terms!!");                //call the validateForm method and return the result to the form element        return v.validateForm();    }    </script> </head> <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;"> <h1>Advanced Usage</h1> <p>This example will output the errors on the page. It deomonstrates how to create your own template for the error messages.</p> <div id="validation_errors"></div> <br /> <form name="contact_us" method="post" action="advanced_example2.html" onsubmit="return validate();" />Enter your Name: <input type="text" id="my_name" value="Chris" /><br />Enter a number: <input type="text" id="my_number" value="89" /><br />Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />Enter some text: <input type="text" id="line1" value="abcdefg" /><br />Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />Do you accept our terms? <input type="checkbox" id="terms" /> <input type="submit" name="submit_button" /></form> </body></html>



In the above code, I create a new ErrorTemplate object and set its properties, then assign it to the validation object to make use of.

The properties we set are:

*Header*
The header can be any HTML you want to appear right above the errors. If you want to put the errors in a HTML list then the header is where you would put the open list tag like <ul> or <ol>. The header section of the template is also useful for a title such as Error!

*Item*
The item section is what will be repeated for each validation error that occurs. In the item section you place a special reference in the code which will be replaced with the actual validation error. The reference which will be replaced is {ERROR_MESSAGE}

*Footer*
The footer section is useful for closing a list if you have opened one in the head section, e.g. </ul> or </ol>.

----------


## the182guy

Even More Advanced Features
You might be thinking that, what if I have a complicated validation to perform? You can write your own custom validation function and just pass it to the Validator, the Validator will then handle it all for you. Just make sure your custom function returns true or false. Example:


javascript Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Easy Form Validation</title>
 <script type="text/javascript" src="easy_validation.js"></script>
<script type="text/javascript">
    
    function validatePasswordFields()
    {
        //this is the custom validation function we use. It can do anything, however it must return true or false.
    
        var pass1 = document.getElementById("password1").value;
        var pass2 = document.getElementById("password2").value;
        
        var output = false;
        
        if(pass1 == pass2)
        {
            output = true;
        }
        
        return output;
    }
    
    function validate()
    {
        var v = new Validator(); //create a new Validator object called v
         //tell the validator to display the errors on the page
        v.setOutputType("DIV");
        //tell the validator which Div to show the errors in
        v.setOutputDivId("validation_errors");
                
        //setup the fields we want to validate
        
        //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE
        v.addField("Your Name",         "NAME",         "my_name");
        
        //add a custom validation function
        v.addCustomValidation(validatePasswordFields, "Passwords do not match!!"); //passing in the function name and the error message to display
        
        //call the validateForm methos and return the result to the form element
        return v.validateForm();
    }
    
</script>
 </head>
 <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;">
 <h1>Advanced Usage</h1>
 <p>This example will output the errors on the page. It deomonstrates how to create your own custom validation for the Validator to handle.</p>
 <div id="validation_errors"></div>
 <form name="contact_us" method="post" action="advanced_example3.html" onsubmit="return validate();" />
Enter your Name: <input type="text" id="my_name" value="Chris" /><br />
Enter a password: <input type="password" id="password1" value="Chris" /><br />
Confirm the password: <input type="password" id="password2" value="Chris" /><br />
 <input type="submit" name="submit_button" />
</form>
 </body>
</html>


In the above example I demonstrate creating a custom validation function and having the Validator handle it for me. The custom validation is to check if two password textboxes match.

For those of you that might argue that a framework like this is going to be too heavy to use  i.e. large download, then you can put the code through an optimiser which will remove all white space and unnecessary characters, this will reduce the file size by a lot.

Such as this one
http://www.xtreeme.com/cgi-bin/js-op...-optimizer.cgi

----------


## the182guy

Conclusion
That's it! Thanks for looking. Comments are welcome, and please rate! You are free to use this in your projects. :wave:

----------

