Pages

Thursday, August 05, 2010

Quick and Easy Javascript Form Validation

If you need a quick javascript form validation script, you can use this one from Javascript-coder.com. Its pretty easy to implement and I've used it in some of my projects already. Its gonna save you some time coding from scratch!

Download the JavaScript form validation script


You can download the JavaScript form validation script here.

The zip file contains the java script file, documentation and examples.

Using the form validation script


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

<script language="JavaScript" src="gen_validatorv31.js" type="text/javascript"></script>
</head>

2. Just after defining your form, Create a form validator object passing the name of the form

<FORM name='myform' action="">
<!----Your input fields go here -->
</FORM>
<SCRIPT language="JavaScript">
var frmvalidator  = new Validator("myform");
....


3. Now add the validations required

frmvalidator.addValidation("FirstName","alpha");

the first argument is the name of the field and the second argument is the validation descriptor, which specifies the type of validation to be performed.
You can add any number of validations. The list of validation descriptors are provided at the end of the documentation.
The optional third argument is the error string to be displayed if the validation fails.

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


4. Similarly, add validations for the fields where validation is required.
That's it! You are ready to go.

Example


The example below will make the idea clearer
<form action="" name="myform" >
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">First Name</td>
<td><input type="text" name="FirstName"></td>
</tr>
<tr>
<td align="right">Last Name</td>
<td><input type="text" name="LastName"></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="Email"></td>
</tr>
<tr>
<td align="right">Phone</td>
<td><input type="text" name="Phone"></td>
</tr>
<tr>
<td align="right">Address</td>
<td><textarea cols="20" rows="5" name="Address"></textarea></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<SELECT name="Country">
<option value="" selected>[choose yours]
<option value="008">Albania
<option value="012">Algeria
<option value="016">American Samoa
<option value="020">Andorra
<option value="024">Angola
<option value="660">Anguilla
<option value="010">Antarctica
<option value="028">Antigua And Barbuda
<option value="032">Argentina
<option value="051">Armenia
<option value="533">Aruba
</SELECT>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
<script language="JavaScript" 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("FirstName","alpha");




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=0");
</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:
  • 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 don not match!',frm.pwd1);
    return false;
    }
    else
    {
    return true;
    }
    }

    sfm_show_error_msg() displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object.

  • 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.
    You will not need this method in most cases.

    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);

    Table of Validation Descriptors









































































    required
    req
    The field should not be empty
    maxlen=???
    maxlength=???
    checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as "maxlen=25"
    minlen=???
    minlength=???
    checks the length of the entered string to the required minimum. example "minlen=5"
    alphanumeric /
    alnum
    Check the data if it contains any other characters other than alphabetic or numeric characters
    alphanumeric_space /
    alnum_s
    Allows only alphabetic, numeric and space characters
    num
    numeric
    Check numeric data (allow only digits)
    dec
    decimal
    Allow numbers (with decimal point)
    alpha
    alphabetic
    Check alphabetic data.
    alpha_s
    alphabetic_space
    Check alphabetic data and allow spaces.
    emailThe field is an email field and verify the validity of the data.
    lt=???
    lessthan=???
    Verify the data to be less than the value passed. Valid only for numeric fields.
    example: if the value should be less than 1000 give validation description as "lt=1000"
    gt=???
    greaterthan=???
    Verify the data to be greater than the value passed. Valid only for numeric fields.
    example: if the value should be greater than 10 give validation description as "gt=10"
    regexp=???Check with a regular expression the value should match the regular expression.
    example: "regexp=^[A-Za-z]{1,20}$" allow up to 20 alphabetic characters.
    dontselect=??This validation descriptor is valid only for select input items (lists) Normally, the select list boxes will have one item saying 'Select One' or some thing like that. The user should select an option other than this option. If the index of this option is 0, the validation description should be "dontselect=0"
    dontselectchkThis validation descriptor is valid only for check boxes. The user should not select th given check box. Provide the value of the check box instead of ?? For example, dontselectchk=on
    shouldselchkThis validation descriptor is valid only for check boxes. The user should select th given check box. Provide the value of the check box instead of ?? For example, shouldselchk=on
    selone_radioChecks whether at least one radio button is selected.

    Example Page



    See the JavaScript form validation example here

    More features of JavaScript Form Validation script


    The JavaScript form validation script has still more advanced features. To know about how to display the form validation error messages together, or about displaying the form on the page itself, see: Form Validation : more features

    Source: http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

    1 comment:

    1. i m using the javascript validator in that the custom script is validating the password and passwordverification field is same or not but its not displaying the error message thats my problem

      ReplyDelete