Using client side JavaScript is an efficient way to validate the user input in web forms. When there are many fields in the form, the JavaScript validation becomes too complex.
The JavaScript class presented here makes the form validations many times easier.
How to add JavaScript Form Validation quickly
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
<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
<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
frmvalidator.addValidation("FirstName","req","Please enter your First Name"); |
The format of the addValidation() function is:
frmvalidator.addValidation(Field Name, Validation Descriptor, Error String); |
The third parameter ( Error string ) is optional.
You can add any number of validations to a field.
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"); |
Example
Here is a complete example:
<form action="" id="myform" > | |
<p> |
<label for='FirstName'>First Name:</label> | |
<input type="text" id="FirstName" name="FirstName" /> |
</p> | |
<p> |
<label for='LastName'>Last Name:</label> | |
<input type="text" id="LastName" name="LastName" /> |
</p> | |
<p> |
<label for='EMail'>EMail:</label> | |
<input type="text" id="EMail" name="EMail" /> |
</p> | |
<p> |
<label for='Phone'>Phone:</label> | |
<input type="text" id="Phone" name="Phone" /> |
</p> | |
<p> |
<label for='Address'>Address:</label> | |
<textarea cols="20" rows="5" id="Address" name="Address"></textarea> |
</p> | |
<p> |
<label for='Country'>Country:</label> | |
<select id="Country" name="Country"> |
<option value="000" selected="selected">[choose yours]</option> | |
<option value="008">Albania</option> |
<option value="012">Algeria</option> | |
<option value="016">American Samoa</option> |
<option value="020">Andorra</option> | |
<option value="024">Angola</option> |
<option value="660">Anguilla</option> | |
<option value="010">Antarctica</option> |
<option value="028">Antigua And Barbuda</option> | |
<option value="032">Argentina</option> |
<option value="051">Armenia</option> | |
<option value="533">Aruba</option> |
</select> | |
</p> |
<p> | |
<input type="submit" name="submit" value="Submit"> |
</p> | ||
</form> | ||
<script type="text/javascript"> | ||
var frmvalidator = new Validator("myform"); | |
frmvalidator.addValidation("FirstName","req","Please enter your First Name"); |
frmvalidator.addValidation("FirstName","maxlen=20", | |
"Max length for FirstName is 20"); |
frmvalidator.addValidation("LastName","req"); | |
frmvalidator.addValidation("LastName","maxlen=20"); |
frmvalidator.addValidation("Email","maxlen=50"); | |
frmvalidator.addValidation("Email","req"); |
frmvalidator.addValidation("Email","email"); | |
frmvalidator.addValidation("Phone","maxlen=50"); |
frmvalidator.addValidation("Phone","numeric"); | |
frmvalidator.addValidation("Address","maxlen=50"); |
frmvalidator.addValidation("Country","dontselect=000"); | |
</script> |
Some Additional Notes
§ The form validators should be created only after defining the HTML form (only after the </form> tag. )
§ Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash.
§ You can’t use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below
Adding a custom validation
If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:
1. Create a javascript function which returns true or false depending on the validation
function DoCustomValidation() | |
{ |
var frm = document.forms["myform"]; | |
if(frm.pwd1.value != frm.pwd2.value) |
{ | |
sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1); |
return false; | |
} |
else | |
{ |
return true; | |
} |
} |
sfm_show_error_msg() function displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object.
2. Associate the validation function with the validator object.
frmvalidator.setAddnlValidationFunction("DoCustomValidation"); |
The custom validation function will be called automatically after other validations.
If you want to do more than one custom validations, you can do all those validations in the same function.
function DoCustomValidation() | |
{ |
var frm = document.forms["myform"]; | |
if(false == DoMyValidationOne()) |
{ | |
sfm_show_error_msg('Validation One Failed!'); |
return false; | |
} |
else | |
if(false == DoMyValidationTwo()) |
{ | |
sfm_show_error_msg('Validation Two Failed!'); |
return false; | |
} |
else | |
{ |
return true; | |
} |
} |
where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation.
Clear All Validations
In some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object.
frmvalidator.clearAllValidations(); |
This function call clears all validations you set.
Set focus on validation failure
By default, if there is a validation error, the focus is set on the input element having the error. You can disable this behavior by calling:
frmvalidator.EnableFocusOnError(false); |
Showing all the form validation errors together in a message box
If you want to show all the error messages together, then just call the EnableMsgsTogether() function as shown below.
frmvalidator.EnableMsgsTogether(); |
Showing the form validation errors on the page itself
You can display the validation errors on the page itself.
Here are the steps:
1. Create a place on the page for displaying the errors
create a DIV on the page for the errors the DIV should be named as{formname}_errorloc
where {formname} is the name of your form.
Example:
<div id='myform_errorloc' class='error_strings'></div> |
2. Enable on-page error display
Call the EnableOnPageErrorDisplaySingleBox() function to enable on page error display.
For example:
frmvalidator.EnableOnPageErrorDisplaySingleBox(); | |
frmvalidator.EnableMsgsTogether(); |
Showing the error messages next to the input element
Here are the steps:
1. Create a place to display the error message next to the input elements
For example place a DIV next to the input element and have it ID of the format:
{formname}_{inputname}_errorloc
Example:
<div id='myform_Name_errorloc' ></div> | |
<input type="text" name="Name" /> |
2. call EnableOnPageErrorDisplay()
frmvalidator.EnableOnPageErrorDisplay(); | |
frmvalidator.EnableMsgsTogether(); |
Conditional Validations
Sometimes it may be required to validate certain fields only on certain conditions. For example, a textbox ‘Other’ needs to be filled only when ‘Other’ radio option is selected.
Here is how to add a condition to a validation:
There is an optional 4th parameter to the addValidation() function. If you pass a condition, that condition will be checked before running the validation.
Example:
frmvalidator.addValidation("hearabout_other","req","Please fill-in this textbox", |
"VWZ_IsChecked(document.forms['myform'].elements['hearabout'],'Other')"); |
VWZ_IsChecked() is a handy function included in gen_validatorv4.js script that can be used to check the ‘checked’ status of radio group or check box. The first parameter is the input object and the second parameter is the value.
If it is a drop down list, you can use the VWZ_IsListItemSelected() function
frmvalidator.addValidation("city_other","req","Please fill-in the city name", | |
"VWZ_IsListItemSelected(document.forms['myform'].elements['city_list'],'Other')"); |
VWZ_IsListItemSelected(list_object, item_value)
The first parameter is the drop down list object and the second is the value of the item.
Triggering the validations when custom submitting the form
The validation script uses the form’s onsubmit event to trigger the validations. If you are submitting the form using code, for example on clicking a hyperlink, the onsubmit event is not triggered :
<a href='#' onClick="document.yourform.submit()">Submit Form</a> |
You can trigger the validations by explicitly calling the form’s onsubmit like this:
<a href='#' onClick="if(document.yourform.onsubmit()){document.yourform.submit()}">Submit Form</a> |
Making it a bit neater:
<a href="javascript: submitform()">Submit</a> | |
<script type="text/javascript"> |
function submitform() | |
{ |
if(document.myform.onsubmit()) | |
{ |
document.myform.submit(); | |
} |
} | |
</script> |
Thank You All...
Happy Coding...
No comments:
Post a Comment