JavaScript Form Validation : quick and easy!

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.

Contents

  1. Download the JavaScript form validation script
  2. Using the form validation script
  3. Adding a custom validation
  4. Table of Validation Descriptors
  5. Showing the form validation errors next to the element
  6. ‘Conditional’ form validations
  7. Form validation without coding!

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.

Just Choose Validations!
Simfatic Forms is a feature-rich web form maker.
You just have to choose the validations. More info & downloads

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="">
     <!----Your input fields go here -->
     </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");
    

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
  2. 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.

  3. Associate the validation function with the validator object.
  4. 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);
    

    Table of Validation Descriptors

    Validation Descriptor Usage
    required or
    req
    The field should not be empty.

    Note that this validation if for fields like Textbox and multi-line text box. For ‘selections’ like drop down and radio group, use an appropriate validation like ‘dontselect’ or ‘selone_radio’.

    maxlen=??? or
    maxlength=???
    Limits the length of the input.
    For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25”
    minlen=??? or
    minlength=???
    Checks the length of the entered string to the required minimum.
    Example “minlen=5”
    alphanumeric or
    alnum
    The input can contain alphabetic or numeric characters only.
    (Note that space or punctuation also are not allowed since those characters are not alpha numeric)
    alphanumeric_space
    alnum_s
    Allows only alphabetic, numeric and space characters
    num
    numeric
    Allow numbers only
    alpha
    alphabetic
    Allow only alphabetic characters.
    alpha_s
    alphabetic_space
    Allows alphabetic and space characters
    email Validates the field to be a proper email address.
    (Note, However that the validation can’t check whether the email address exists or not)
    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=??? Match the input with a regular expression.
    Example: “regexp=^[A-Za-z]{1,20}$” allow up to 20 alphabetic characters.
    dontselect=?? This validation descriptor is valid only for drop down lists. The drop down select list boxes usually will have one item saying ‘Select One’ (and that item will be selected by default). The user should select an option other than this ‘Select One’ item.
    If the value of this default option is ‘000’, the validation description should be “dontselect=000”

    Dropdown box with default selected

    Drop down list source

    dontselectchk=?? This validation descriptor is only for check boxes. The user should not select the given check box. Provide the value of the check box instead of ??
    For example, dontselectchk=on
    shouldselchk=?? This validation descriptor is only for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
    For example, shouldselchk=on
    selone_radio One of the radio buttons should be selected.
    Example:
    chktestValidator.addValidation("Options","selone");
    
    Compare two input elements
    eqelmnt=??? Compare two input elements. For example: password and confirm password. Replace ??? with the name of the other input element.
    Example:
    frmvalidator.addValidation("confpassword","eqelmnt=password",
     "The confirmed password is not same as password");
    
    neelmnt=??? The value should not be equal to the other input element
    Example:
    frmvalidator.addValidation("password","neelmnt=username",
    "The password should not be same as username");
    
    ltelmnt=??? The input should be less than the other input. Give the name of the other input instead of ???
    leelmnt=??? The input should be less than or equal to the other input. Give the name of the other input instead of ???
    gtelmnt=??? The input should be greater than the other input. Give the name of the other input instead of ???
    geelmnt=??? The input should be greater than or equal to the other input. Give the name of the other input instead of ???

    Go to the second part of this post to learn about the advanced features of this validation script.

    Learn More

    Javascript Form validation Video Tutorial


Comments on this entry are closed.

  • Try to include the scripts in a ASP Master Page (which is the only one with a statement called “form1”), but keep getting the error “Couldnot get the Form object form1”
    Any idea why?

    Thanks

  • Thanks so much for this valuable info,is appreciated a lot, thanks again
    greetings from México

  • I need some math function with javascrpit

    i want to plus 3 item and use with leelmnt function way u help me thank you to all

    frmvalidator.addValidation(“item1″,”leelmnt=item2+item3+item4″,”Desciription”);

  • This is great !!! Makes life so much easier. I am looking to change the color of error messages. Is there a way to do that ?

  • The “numeric” descriptor doesn’t allow decimal points. So 10 is a valid entry, but 10.00 or 10.50 is not. Is there any way to fix this? (Going to alphanumeric wouldn’t work – that would allow letters, which we don’t want for numbers).

    • Can anyone help with this? thanks!

  • Hello Support,

    I’ve just discovered your JavaScript validation library and I’m considering using it, but before I do I have a few issues to resolve. The big issue for me is executing a PHP action after completing my validation. My form element is defined as:

    The validation works fine, but the action fails because this test fails: if (isset($_POST[‘submit’])) {

    Any idea why?

    Also, I’d like to give my users some feedback as they are filling out the form. I’d like to change an asterisk next to required fields from red to green. But I have no idea how to do this. And, finally, I’d like to thank the user before/(after?) clearing the form. I should mention that I’ve changed the message alerts to a text element on the form.

    Thanks for your assistance and thanks for creating an excellent library.

    -Merwyn

  • Hi there, i was wondering if we are allowed to use your javascript validator?

    • yes, of course. Free for commercial /non commercial use

  • hi sir ..
    form validation demo was not completed .. drop down box and phone box do not validate ….. pls check

  • Many thanks for the script and it’s helpful on making validation on the html form.

    I’ve encounter a weird situation as I’ve 3 form on 3 different html page, the validation are similar but the validation contain chinese characters in the error message. I’ve modified the below to make it supports double byte characters.

    One form are working fine with this setting but the other 2 are not, it simply skip the validation on submit the form, but if I change the message into english then the validation is working on those 2 pages. I couldn’t find out where’s the problem, do you have any advice on this situation?

  • I’m having a problem with some condional checking. My form uses ajax to pull in some database data in response to selections made – that part is working fine, and validating. I have a radio button set (named ‘div_id’) which is used to diaplay different form elements depending on the users requirements (in my case either a book chapter or a journal article).

    frmvalidator.addValidation(“publisherb”,”req”,”Please enter the publisher”,”VWZ_IsChecked(document.forms[‘myform’].elements[‘div_id’],’b’)”); works fine but
    frmvalidator.addValidation(“extract_authorsb”,”req”,”Please enter the chapter or book author”,”VWZ_IsChecked(document.forms[‘myform’].elements[‘div_id’],’b’)”); doesn’t.

    The b at the end of the field name defines that the selection used was ‘b’ for book the journal option has j at the end and similar validation lines are in place.

    I have 16 of these conditional validations in place (8 for each). Testing my form, the first two tests (in my script) work, but once data has been entered into those two fields the form is then submitted with lots of missing data.

    Have I missed something?

  • How do I force an user not to use ” ‘ in the input fields?

    Thanks

    • Use the regexp vaildation.

  • This works fine on HTML pages. But when I implement it on jsp pages it doesn’t work. Could you explain why?

  • Thank you for this script, it has made life much easier. I could use some help with a particular case…

    I have a form which contains static elements (e.g. Name, Phone) and also contains dynamically created elements which pass values as arrays (e.g. filename[1], filename[3]).

    The script validates all the static elements, but I can’t get it to verify the array values. Any suggestions?

  • I call EnableMsgsTogether and the messages are displayed properly in the alert window, but they are followed by a list of “undefined”. I’ve been trying to debug for hours..

    Any ideas?

  • Download the script, added the js script to the website and then added the validation after the tag.

    Tested the form and nothing happened. No validation, nothing.

    Only difference between my form and the demo is I use CSS to format and position the text.

    Any solutions for thgis problem

    Thanks

    • Need to see the form page to see what is wrong.

  • nevermind… just found out that if i put in about 6 spaces after the phrases, it works fine. What the hell was Chrome thinking?!!

  • College Name:

    Enter College Details

    College Name

    College Location

    Enter HOD Phone number

    var frmvalidator = new Validator(“enquiry”);
    frmvalidator.addValidation(“collegeid”,”req”,”select college id”);
    frmvalidator.addValidation(“collegename”,”req”,”select college name”);//17
    ———-
    once click on addcollege, i am getting the fields, but validation is not working for this fields and after these fields. iam getting message like javascript error.
    please give me a solution

  • Thanks for your trouble and efforts for the script and advice to everyone.

    If there is more than one error on a form, then the user fixes that one error, it will submit with the other errors without checking the form again. I’m sure this is a simple fix, but I’m not sure how to do it. I’m obviously a noob, and any help would be appreciated. – Thanks

    • After trial and error I have found a way around the problem. I was using a “req” for the Name field and “email” for the next field that was the email. If I would correct the name but still leave the email blank, it would submit anyhow with a blank email. I solved it by using multiple validations. (Maybe this is the way you are supposed to do it, I don’t know.) I used the “req” for the email to make sure data is entered, then used the “email” validation right after it to make sure it is formatted correctly. This seems to work fine.

      This form validation script is the neatest thing since sliced bread for us non-programmers. THANKS!

  • i have 3 fields no_of_males,no_of_childrens,no_of_females and i have to make the validation that sum of these field input should be at least one.Please tell me how to do that using your validation script .I know this can be made by making manually but i am already using a manual function and i can’t write this functionality into that function.

  • anybody have a solution for chrome chopping off all the javascript popup error messages?

    Ex: Email: Enter a valid email addr…