Search This Blog

Tuesday, February 28, 2012

JavaScript Form Validation : quick and easy!

JavaScript Form Validation : quick and easy!:

How to add JavaScript Form Validation quickly

First, download the JavaScript form validation script here.
The zip file contains the javascript file, examples.

The script has a catalog of almost all the common validation types built-in.

The idea is to create a set of “validation descriptors” associated with each element in a form. The “validation descriptor” is nothing but a string specifying the type of validation to be performed.

Each field in the form can have zero one or more validations. For example, you can have an input field that should not be empty, should be less than 25 chars and should be alpha-numeric.

In other words, in order to validate a field, you just associate a set of validation descriptors for each input field in the form.

Using the form validation script

  1. Include gen_validatorv4.js in your html file just before closing the HEAD tag
  2. <script src="gen_validatorv4.js" type="text/javascript">script>
    head>
  3. Just after defining your form, create a Validator() object passing the name of the form
  4. <form id='myform' action="">
    form>
    <script type="text/javascript">
    var frmvalidator = new Validator("myform");
    //where myform is the name/id of your form
  5. Now, add the validations required
  6. frmvalidator.addValidation("FirstName","req","Please enter your First Name");

    The format of the addValidation() function is:

    frmvalidator.addValidation(Field Name, Validation Descriptor, Error String);

    See below for the complete list of validation descriptors. The third parameter ( Error string ) is optional.
    You can add any number of validations to a field.

    frmvalidator.addValidation("FirstName","req","Please enter your First Name");
    frmvalidator.addValidation("FirstName","maxlen=40",
    "Max length for FirstName is 40");

No comments:

Post a Comment