Form Validation Using Java-Script

In order to validate a field, you just associate a set of validation descriptors for each input field in the form. 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.

Steps to embed the form validation script:–

1.Include gen_validatorv4.js in your html file just before closing the HEAD tag

1
2
<script src="gen_validatorv4.js" type="text/javascript"></script>
     </head>

2.Just after defining your form, create a Validator() object passing the name of the form

1
2
3
4
5
<form id='myform' action="">
       <!----Your input fields go here -->
        </form>
       <script type="text/javascript">
       var frmvalidator  = new Validator("myform");     //where myform is the name/id of your form

3.Now, add the validations required. The format of the addValidation() function is:

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

For e.g , Adding validation to FirstNanme as a reuired field and limiting maximum length to 40.

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