[Javascript OOP] - Easy Form Validation-VBForums
Results 1 to 5 of 5

Thread: [Javascript OOP] - Easy Form Validation

  1. #1

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Arrow [Javascript OOP] - Easy Form Validation

    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:
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    5. <title>Easy Form Validation</title>
    6.  
    7. <script type="text/javascript" src="easy_validation.js"></script>
    8. <script type="text/javascript">
    9.    
    10.     function validate()
    11.     {
    12.         var v = new Validator(); //create a new Validator object called v
    13.        
    14.         //setup the fields we want to validate
    15.        
    16.         //          NAME                VALIDATION      ELEMENT ID
    17.         v.addField("Your Number",       "NUMBER",       "my_number");
    18.         v.addField("Your Date",         "DATE",         "dob");
    19.         v.addField("Your Text",         "NOT_EMPTY",    "line1");
    20.         v.addField("Email address",     "EMAIL",        "email");
    21.         v.addField("Terms",                       "CHECKBOX",       "terms");
    22.        
    23.         //call the validateForm method and return the result to the form element
    24.         return v.validateForm();
    25.     }
    26.    
    27. </script>
    28.  
    29. </head>
    30.  
    31. <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;">
    32.  
    33. <h1>Simple Usage</h1>
    34.  
    35. <form name="contact_us" method="post" action="simple_example.html" onsubmit="return validate();" />
    36. Enter a number: <input type="text" id="my_number" value="89" /><br />
    37. Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />
    38. Enter some text: <input type="text" id="line1" value="abcdefg" /><br />
    39. Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />
    40. Do you accept our terms? <input type="checkbox" id="terms" />
    41.  
    42. <input type="submit" name="submit_button" />
    43. </form>
    44.  
    45. </body>
    46. </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 validate
    • CUSTOM_ERROR_MESSAGE - This is optional, if set it will override the default error message
    • VALIDATION_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.
    Attached Files Attached Files
    Last edited by the182guy; Nov 15th, 2008 at 12:19 PM.
    Chris

  2. #2

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: [Javascript OOP] - Easy Form Validation

    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:
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    5. <title>Easy Form Validation</title>
    6.  
    7. <script type="text/javascript" src="easy_validation.js"></script>
    8. <script type="text/javascript">
    9.    
    10.     function validate()
    11.     {
    12.         var v = new Validator(); //create a new Validator object called v
    13.        
    14.         //tell the validator to display the errors on the page
    15.         v.setOutputType("DIV");
    16.         //tell the validator which Div to show the errors in
    17.         v.setOutputDivId("validation_errors");
    18.        
    19.         //setup the fields we want to validate
    20.        
    21.         //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE
    22.         v.addField("Your Name",         "NAME",         "my_name");
    23.         v.addField("Your Number",       "NUMBER",       "my_number");
    24.         v.addField("Your Date",         "DATE",         "dob");
    25.         v.addField("Your Text",         "NOT_EMPTY",    "line1");
    26.         v.addField("Email address",     "EMAIL",        "email");
    27.         v.addField("Terms",             "CHECKBOX",     "terms",        "You must accept our terms!!");
    28.        
    29.         //call the validateForm method and return the result to the form element
    30.         return v.validateForm();
    31.     }
    32.    
    33. </script>
    34.  
    35. </head>
    36.  
    37. <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;">
    38.  
    39. <h1>Advanced Usage</h1>
    40.  
    41. <p>This example will output the errors on the page.</p>
    42.  
    43. <div id="validation_errors"></div>
    44.  
    45. <form name="contact_us" method="post" action="advanced_example.html" onsubmit="return validate();" />
    46. Enter your Name: <input type="text" id="my_name" value="Chris" /><br />
    47. Enter a number: <input type="text" id="my_number" value="89" /><br />
    48. Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />
    49. Enter some text: <input type="text" id="line1" value="abcdefg" /><br />
    50. Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />
    51. Do you accept our terms? <input type="checkbox" id="terms" />
    52.  
    53. <input type="submit" name="submit_button" />
    54. </form>
    55.  
    56. </body>
    57. </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.
    Last edited by the182guy; Nov 15th, 2008 at 12:20 PM.
    Chris

  3. #3

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: [Javascript OOP] - Easy Form Validation

    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:
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    5. <title>Easy Form Validation</title>
    6.  
    7. <script type="text/javascript" src="easy_validation.js"></script>
    8. <script type="text/javascript">
    9.    
    10.     function validate()
    11.     {
    12.         var v = new Validator(); //create a new Validator object called v
    13.        
    14.         //tell the validator to display the errors on the page
    15.         v.setOutputType("DIV");
    16.         //tell the validator which Div to show the errors in
    17.         v.setOutputDivId("validation_errors");
    18.        
    19.         var t = new ErrorTemplate(); //create a new template object
    20.         t.setHeader ("<h2 style='color:red;'>Oops! Some errors occured!!</h2>");
    21.         t.setItem   ("<img src='x.gif' alt='error' /> {ERROR_MESSAGE}<br />"); //this line will be reprated with each error
    22.         t.setFooter ("<br />Please correct these errors.");
    23.        
    24.         v.setErrorTemplate(t); //assign the new template object to the Validator for use
    25.        
    26.         //setup the fields we want to validate
    27.        
    28.         //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE
    29.         v.addField("Your Name",         "NAME",         "my_name");
    30.         v.addField("Your Number",       "NUMBER",       "my_number");
    31.         v.addField("Your Date",         "DATE",         "dob");
    32.         v.addField("Your Text",         "NOT_EMPTY",    "line1");
    33.         v.addField("Email address",     "EMAIL",        "email");
    34.         v.addField("Terms",             "CHECKBOX",     "terms",        "You must accept our terms!!");
    35.        
    36.         //call the validateForm method and return the result to the form element
    37.         return v.validateForm();
    38.     }
    39.    
    40. </script>
    41.  
    42. </head>
    43.  
    44. <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;">
    45.  
    46. <h1>Advanced Usage</h1>
    47.  
    48. <p>This example will output the errors on the page. It deomonstrates how to create your own template for the error messages.</p>
    49.  
    50. <div id="validation_errors"></div>
    51.  
    52. <br />
    53.  
    54. <form name="contact_us" method="post" action="advanced_example2.html" onsubmit="return validate();" />
    55. Enter your Name: <input type="text" id="my_name" value="Chris" /><br />
    56. Enter a number: <input type="text" id="my_number" value="89" /><br />
    57. Enter a date: <input type="text" id="dob" value="01/01/2008" /><br />
    58. Enter some text: <input type="text" id="line1" value="abcdefg" /><br />
    59. Email address: <input type="text" id="email" value="chris@chriscrossonline.co.uk" /><br />
    60. Do you accept our terms? <input type="checkbox" id="terms" />
    61.  
    62. <input type="submit" name="submit_button" />
    63. </form>
    64.  
    65. </body>
    66. </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>.
    Last edited by the182guy; Nov 15th, 2008 at 12:20 PM.
    Chris

  4. #4

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: [Javascript OOP] - Easy Form Validation

    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:
    1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2. <html xmlns="http://www.w3.org/1999/xhtml">
    3. <head>
    4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    5. <title>Easy Form Validation</title>
    6.  
    7. <script type="text/javascript" src="easy_validation.js"></script>
    8. <script type="text/javascript">
    9.    
    10.     function validatePasswordFields()
    11.     {
    12.         //this is the custom validation function we use. It can do anything, however it must return true or false.
    13.    
    14.         var pass1 = document.getElementById("password1").value;
    15.         var pass2 = document.getElementById("password2").value;
    16.        
    17.         var output = false;
    18.        
    19.         if(pass1 == pass2)
    20.         {
    21.             output = true;
    22.         }
    23.        
    24.         return output;
    25.     }
    26.    
    27.     function validate()
    28.     {
    29.         var v = new Validator(); //create a new Validator object called v
    30.  
    31.         //tell the validator to display the errors on the page
    32.         v.setOutputType("DIV");
    33.         //tell the validator which Div to show the errors in
    34.         v.setOutputDivId("validation_errors");
    35.                
    36.         //setup the fields we want to validate
    37.        
    38.         //          NAME                VALIDATION      ELEMENT ID      CUSTOM ERROR MESSAGE
    39.         v.addField("Your Name",         "NAME",         "my_name");
    40.        
    41.         //add a custom validation function
    42.         v.addCustomValidation(validatePasswordFields, "Passwords do not match!!"); //passing in the function name and the error message to display
    43.        
    44.         //call the validateForm methos and return the result to the form element
    45.         return v.validateForm();
    46.     }
    47.    
    48. </script>
    49.  
    50. </head>
    51.  
    52. <body style="font-size:13px;font-family:Arial, Helvetica, sans-serif;">
    53.  
    54. <h1>Advanced Usage</h1>
    55.  
    56. <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>
    57.  
    58. <div id="validation_errors"></div>
    59.  
    60. <form name="contact_us" method="post" action="advanced_example3.html" onsubmit="return validate();" />
    61. Enter your Name: <input type="text" id="my_name" value="Chris" /><br />
    62. Enter a password: <input type="password" id="password1" value="Chris" /><br />
    63. Confirm the password: <input type="password" id="password2" value="Chris" /><br />
    64.  
    65. <input type="submit" name="submit_button" />
    66. </form>
    67.  
    68. </body>
    69. </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
    Chris

  5. #5

    Thread Starter
    Frenzied Member the182guy's Avatar
    Join Date
    Nov 2005
    Location
    Cheshire, UK
    Posts
    1,473

    Re: [Javascript OOP] - Easy Form Validation

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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.