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.

  • I love this script, its easy and works perfect!!! The only thing I do not like is the popup error message. Is there anyway to alter the script so the error message displays in the form field instead?
    I would keep the popup box if I could stop the website address from showing up above the error and just show the error

  • Woah! I’m really loving the template/theme of this website. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and appearance. I must say that you’ve done a fantastic job with this. Additionally, the blog loads very quick for me on Chrome. Excellent Blog!

  • Hello, I used this code and it seem to work correctly, the only problem is the email validation, it seems that the script is skipping it all together. It goes directly to the phone number part.

    Any Ideas?

    this is the code that I have used:

    function docload()
    {
    var frmvalidator = new Validator(“bidrequest”);
    if(frmvalidator.addValidation)
    {
    frmvalidator.addValidation(“CompanyName”,”req”,”Please enter the company Name”);
    frmvalidator.addValidation(“CompanyName”,”maxlen=50″,”Max length for company name is 50 characters”);
    frmvalidator.addValidation(“Contact”,”req”,”Please enter the contact name”);
    frmvalidator.addValidation(“Contact”,”maxlen=30″,”Max length for contact name is 30 characters”);
    frmvalidator.addValidation(“Email”,”maxlen=50″);
    frmvalidator.addValidation(“Email”,”req”,”Please enter a valid E-mail”);
    frmvalidator.addValidation(“Email”,”email”);
    frmvalidator.addValidation(“Phone”,”req”,”Enter the phone number please”);
    frmvalidator.addValidation(“Phone”,”maxlen=30″,”Max lenght is 30″);
    frmvalidator.addValidation(“Phone”,”numeric”,”Only numbers please”);
    frmvalidator.addValidation(“Fax”,”numeric”,”req”,”Enter the phone number please”);
    frmvalidator.addValidation(“Address1″,”req”,”maxlen=100″,”Enter the address please”);
    frmvalidator.addValidation(“Address2″,”maxlen=100”);
    frmvalidator.addValidation(“Country”,”dontselect=000″);
    frmvalidator.addValidation(“State”,”dontselect=000″);
    frmvalidator.addValidation(“City”,”alpha”,”req”,”Please insert your City”);
    frmvalidator.addValidation(“Zip”,”req”,”numeric”);
    frmvalidator.addValidation(“SourceLanguage”,”req”,”Please insert the Source Language”);
    frmvalidator.addValidation(“TargetLanguage”,”req”,”Please insert the Target Language”);

    /*var chktestValidator = new Validator(“bidrequest”);
    chktestValidator.EnableOnPageErrorDisplaySingleBox();
    chktestValidator.EnableMsgsTogether();

    chktestValidator.addValidation(“NewProject”,”selectradio”,”Is this a new project? Plese select the one'”);
    chktestValidator.addValidation(“Revision”,”selectradio”,”Is this a Revsion? Plese select the one'”);
    chktestValidator.addValidation(“Glossary”,”selectradio”,”Any Glossary Development? Please select one'”);*/
    }
    }

    One more thing, if I want to validate the radio button the whole validation script stops working.

    What am I doing wrong?

    Manu

    • Actually the last thing that validates is the phone number!

      • Solved for the most part, the radio buttons are giving me grief. I changed the code:

        frmvalidator.addValidation(“NewProject”,”selectradio”,”Is this a new project?”);
        frmvalidator.addValidation(“Revision”,”selectradio”,”Is this a Revsion?”);
        frmvalidator.addValidation(“Glossary”,”selectradio”,”Any Glossary Development?”);

        this is what I am using now

        Thanks

  • I was wondering if anyone has come across the issue of the validator not working in IE8? is there a fix or am i missing a command?

    js code:
    var validator = new Validator(‘register’);
    validator.addValidation(‘firstname’,’req’, ‘* Please enter your First Name’);
    validator.addValidation(‘lastname’,’req’, ‘* Please enter your Last Name’);
    validator.addValidation(‘address1′,’req’, ‘* Please enter your Address’);
    validator.addValidation(‘city’,’req’, ‘* Please enter your City’);
    validator.addValidation(‘zip’,’req’, ‘* Please enter your Zipcode’);
    validator.addValidation(‘zip’,’num’, ‘* Example 90045’);
    validator.addValidation(‘zip’,’maxlen=5′, ‘* Example 90045’);
    validator.addValidation(‘zip’,’minlen=5′, ‘* Example 90045′);
    validator.addValidation(’email’,’req’, ‘* Please enter a valid Email Address’);
    validator.addValidation(’email’,’email’, ‘* Please enter a valid Email Address’);
    validator.addValidation(’email’,’regexp=’+emailRegex, ‘* Example email@test.com‘);
    validator.addValidation(‘phone’, ‘req’, ‘* Please enter a valid Phone Number’);
    validator.addValidation(‘phone’, ‘regexp=’+phoneRegex, ‘* Example 123-456-7890’);
    validator.addValidation(‘text483’, ‘req’, ‘* Please select a Division’);
    validator.addValidation(‘text483’, ‘dontselect=””‘, ‘* Please select a Division’);
    validator.addValidation(‘text485’, ‘req’, ‘* Please select a Degree Program’);
    validator.addValidation(‘text485’, ‘dontselect=””‘, ‘* Please select a Degree Program’);
    validator.addValidation(‘text487’, ‘req’, ‘* Please select a Location’);
    validator.addValidation(‘text487’, ‘dontselect=””‘, ‘* Please select a Location’);
    validator.addValidation(‘text489’, ‘req’, ‘* Please select a Term’);
    validator.addValidation(‘text489’, ‘dontselect=””‘, ‘* Please select a Term’);
    validator.EnableOnPageErrorDisplay();
    validator.EnableMsgsTogether();

    • Could you post the link to the form page?

      • its on a localhost, still in testing.

    • what are you doing with +phoneRegex, i that does not work for me??

  • How do I write a code to validate personal identification for the following:
    First Character is either alphabet S or T
    this is followed by seven numeric digits
    Final alphabet character

    without any spaces

    thanks

  • Hello and thank you so much for the awesome tutorial! I have a few questions: How do I add a validation to validate the format of an email address? Your tutorial is great, but I’m sort of a newb when it comes to Java… ok, a TOTAL newb…lol

    This is what I have so far and everything works GREAT, so a HUGE thank you:

    var frmvalidator = new Validator(“form1”);
    frmvalidator.addValidation(“fname”,”req”,”Please enter your First Name”);
    frmvalidator.addValidation(“fname”,”minlen=2″,”Minimum length for First Name is 2 characters”);
    frmvalidator.addValidation(“fname”,”maxlen=20″,”Max length for First Name is 20 characters”);
    frmvalidator.addValidation(“lname”,”req”,”Please enter your Last Name”);
    frmvalidator.addValidation(“lname”,”minlen=2″,”Minimum length for Last Name is 2 characters”);
    frmvalidator.addValidation(“lname”,”maxlen=20″,”Max length for Last Name is 20 characters”);
    frmvalidator.addValidation(“email”,”req”,”Please enter a Valid Email Address”);
    frmvalidator.addValidation(“email”,”maxlen=50″);
    frmvalidator.addValidation(“phone”,”req”,”Please enter your 10-digit Phone Number. Example: 5051234567″);
    frmvalidator.addValidation(“phone”,”minlen=10″,”Please enter your 10-digit Phone Number. Example: 5051234567″);
    frmvalidator.addValidation(“phone”,”maxlen=10″,”Please enter your 10-digit Phone Number. Example: 5051234567″);
    frmvalidator.addValidation(“phone”,”numeric”);
    frmvalidator.addValidation(“state”,”dontselect=000″,”Please select your state”);
    frmvalidator.addValidation(“zcode”,”req”,”Please enter your 5-digit Zip Code”);
    frmvalidator.addValidation(“zcode”,”minlen=5″,”Please enter your 5-digit Zip Code”);
    frmvalidator.addValidation(“zcode”,”maxlen=5″,”Please enter your 5-digit Zip Code”);

    I want to use this regex to validate emails, but I am completely clueless how to use it properly: /^[-a-z0-9~!$%^&*_=+}{\’?]+(\.[-a-z0-9~!$%^&*_=+}{\’?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i

    • You have to escape the regular expression properly. See:
      http://simonwillison.net/2006/Jan/20/escape/

    • Why not use:
      frmvalidator.addValidation(“email”,”email”,”Please enter a Valid Email Address”);

  • This is a great script that I’ve used for a few years, but it seems to have an obscure bug. Specifically, if you use custom validation and the user makes an error related to that validation plus one or more errors relating to standard validation rules then it works fine. But if the only error is related to the custom validation, then it does not submit, but it also does not show the error message. The example code “custom-validation-example.html” manifests this problem. Try entering “Bob” as “First Name” and valid entries for “Last Name” and “Email”. Bob is NOT told to go away! Sorry! Great if you can fix this.

    • Thanks for pointing this out. Updating the custom validation will correct it:
      [code]
      function DoCustomValidation()
      {
      var frm = document.forms["myform"];
      if(frm.FirstName.value == 'Bob')
      {
      sfm_show_error_msg("Bob, you can't submit this form. Go away! ", frm.FirstName);
      return false;
      }
      return true;
      }
      [/code]

  • Hi,
    Is there any way to find out if all required fields are valid before submitting the form?
    Or to make an additional operation when some errors occurs?

    Thanks!

  • Just wanted to say thanks for this, really helpful 🙂

  • WOW…this is AWESOME. Thank you so much for posting it. I am using it on the contact form on my website.

    One question: is there a way use the same popup delivered for the email field (the “Please enter an email” text that shows under the field itself instead of in a popup window) for all fields instead of having a popup window?

    Again….thank you for the awesome script. 😀 You said easy……and for once, that’s EXTREMELY accurate. 🙂

  • very useful information. I recently stumbled across http://rindovincent.blogspot.com where there was a simple JavaScript for validating a form. I hope it will be useful for all the beginners.

  • Great work, I’ve easily implemented. Thanks a lot 🙂

  • i’m trying to add custom validations to check file extensions on two upload fields. the first is required the second isn’t and they should have the same allowed file extensions. i see there is the “accept” rule for jquery but i haven’t figured out how to use it as custom validations. i.e. not sure how to create the custom function and not sure where to place custom function once created. thanks in advance, and nice script.

  • Hi,

    I’m struggling to get radio group validation to work?

    Here: http://www.laticsdrivertraining.com/laticsdraft/sagepay/checkout.php

    I’ve added “chktestValidator.addValidation(“experience”,”selone”,”Please select from experience”);”

    Radio buttons are like so:

    Any help would be appreciated.

    Thanks

  • hi, i used contact form according to your tutorial, everything is fine except

    Client side verification

    server side verification is perfect, but my code is not working on client side.
    , i tried many things but they are not working, please suggest me the solutions

  • Hi, super tool and simple to get it going. One question, I have buold some CRUD screens to execute some transactions and this tool helps a lot in having the users fillin the correct info. How do I program a “cancel” action? I have now used but when pushing this button the checks are fired, what should be done only when the “accept” button is pushed.
    Help highly appreciated.
    Thx Hans

    • perhaps use simple hyperlink or general button for cancel rather than ‘submit’?

      • Hi, what do you mean by general button? I now have a input-submit button, that calls a php-script for all transactions. That script executes a header statement for opening the form to continue. Also for cancel. Now the cancel is blocked because not all requered fields have been entered, what is not so nice for the users.
        So I need a button that passes or prevent the validator statements to execute and does open an other html page. Hyperlinks do not function that well, hence the header statement.
        Do you have a suggestion or example?

        Kind regards
        Hans

  • Hi, I’m creating a form with validation based on your excellent tutorial. Unfortunately the validation does not function b/c of issues with the eqelmnt and dontselect validations.

    The code I have used is below. Any idea of what may be causing the issue?

    Thank-you very much,

    Miles

    var frmvalidator = new Validator(“contactform”);

    frmvalidator.addValidation(“name”,”req”,”Please provide your first and last name”);

    frmvalidator.addValidation(“email”,”req”, “Please provide your email address”);

    frmvalidator.addValidation(“confirm_email”,”eqelmnt=email”, “The email address provided is not formatted correctly”);
    frmvalidator.addValidation(“How_did_you_hear_about_us”,”dontselect=select_one”, “How did you find me?”);

    frmvalidator.addValidation(“comment”,”req”, “Please enter your message);

    • Need to see your form to troubleshoot. Can you post the link to your form?

      • Hi Prasanth, I put the website link in the website text field but it doesn’t show up on the posted comment. So just to be certain it is:

        http://hoganwood.com/contacta.html

        Thank-you,

        Miles

        • The string

          addValidation(“comment”,”req”, “Please enter your message <- is not closed

          Also,
          mailto is too old method. See some contact forms

          use firebug

  • Can someone help me with the code to do the following:

    If textfield1 is filled in make textfield2, textfield3 and textfield4 required.

    Thanks

  • Hi,
    First thank you for your lib that is great.

    I’ve found a little probleme when use this lib with other javascript lib.

    In functions “div_clearmsg” “div_showmsg” you do a “for(var m in msgs)” where msg is an array. Sometime other lib overide the Array object and so your “for” iterate over the element of the array plus the new property of the Array object. And after the code bug.

    I replace your for with for(var i=0 ; i < msgs.length ; i++).

    I found this problem using this calandar lib and http://www.nogray.com/calendar.php#options and your validator.

    Best Regards.

    • Olivier,
      Thank you very much for the heads up!

  • @prasanth- I need to display a message after the form is submitted, is there any way to do this? I have tried alot of diffrent things and cannot get it? is this possible?

    • John,
      In that case, you have to use ajax submission.
      You can redirect from the server side script as well

      • Is there instruction on how to run an ajax submission with this validator anywhere on this site? Any additional help would be great!

        • I need Ajax style of validation sample too.
          Now I directly call form_submit_handler() but got error:
          Uncaught exception: TypeError: Cannot convert ‘document.error_disp_handler’ to object

          Error thrown at line 159, column 4 in form_submit_handler() in …. gen_validatorv4.js:
          document.error_disp_handler.clear_msgs();

          • I had found the solution, but cannot post here – JS code is filtered out. 🙁