jQuery Live Form Validation

After trying a load of non intuitive and not very useful jQuery form validation plugins I came up with this plugin. Its a jQuery plugin which helps create easy form validations with high flexibility and a large set of options.

Demo: Click Here
Advanced Demo: Click Here
Download: Click Here
Project Repository: Click Here

Features:
  • Supports custom validations
  • Options to toggle between live and onsubmit validations
  • Completely customizable CSS
Usage:
  • In the head section add the following code:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script src="javascripts/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">
                jQuery(function(){
                    jQuery("#<id of field to be validated>").validate({
                        expression: "if (<expression for validation>) return true; else return false;",
                        message: "<message on validation failure>"
                    });
                });
    </script>
  • Add the form in the body as shown below

    <form action="" method="post">
    <input type="text" name="<name of field to be validated>" id="<id of field to be validated>" />
    <input type="submit" value="Submit" />
    </form>

That’s it you are done!

For advanced users:

Options:
  • expression: The javascript code which should have two outputs
    or . The value of the field is given by . As this is a string escape characters for backslash and other non standard characters must be used. (Default: return true;)
  • message: The validation message for the field. (Default: “”)
  • error_class: The CSS class of the error message container. (Default: “ValidationErrors”)
  • error_field_class: The CSS class added to the field when found invalid. (Default: “ErrorField”)
  • live: Sets whether the validation of the field should be live or on form submit. (Default: true)

43 Responses to “jQuery Live Form Validation”

  1. Kas says:

    You can add a switch as ‘alert’

    //jQuery(id).after(” + options['message'] + ”);
    jQuery(id).after(‘alert(“‘ + options['message'] + ‘”);’);

    I used,it’s good

  2. Vayu says:

    Hej.

    This is very nice! Well done.

    I have a question though. I am no expert on javascript or jquery, so I was wondering if you could tell me how to make this form be submitted with ajax. In other words, the page shouldnt refresh, but rather the form should be submitted with ajax without reloading.

    I have tried, but without luck.

    Thanks
    Vayu

    • GeekTantra says:

      Hi,

      Thanks for your appreciation.
      If you want the form to be submitted by ajax add the following code to the head section of your html. When the id of your form is "e;FormID"e;

      <script type=”text/javascript”>
      /* <![CDATA[ */
      jQuery(function(){
          jQuery("#FormID").submit(function(){
            jQuery.post('{Replace with URL of the post submission}', jQuery("#FormID").serialize(), function(data){
              jQuery("#FormID").html(data);
            });
            return false;
          });
      });
      /* ]]> */
      </script>

      Hope this helps. Get back if you face any problems.

      Geektantra

  3. Vayu says:

    Hi again.

    Thanks for your help. I really appreciate it.
    However, if I do this then it will submit the form and skip the live validation. Its only supposed to submit if all the input fields are filled in correctly. I know I can validate with php after its been sent, but I want to use the jquery plugin you created for this. :-)

    Thanks
    vayu

    • GeekTantra says:

      Hi Vayu,

      You must put the validation code above the submission code as in the advanced demo form so as to enable the validation also.

      Both the scripts must be there i.e. the validation and submission. I only gave you the submission script in the comment above for your reference.

      Thanks
      GeekTantra.

      • Vayu says:

        Thanks GeekTantra.

        Sorry for keep on bothering you. :-)

        Yes, I had done that. But when I run it, and press the submit button without filling any of the fields, it skips the validation and submits the empty form.

        Here’s what I did see the last bit where I added the submit part:

        jQuery(function(){
        jQuery(“#ValidField”).validate({
        expression: “if (VAL) return true; else return false;”,
        message: “Please enter the Required field”
        });
        jQuery(“#ValidNumber”).validate({
        expression: “if (!isNaN(VAL) && VAL) return true; else return false;”,
        message: “Please enter a valid number”
        });
        jQuery(“#ValidInteger”).validate({
        expression: “if (VAL.match(/^[0-9]*$/) && VAL) return true; else return false;”,
        message: “Please enter a valid integer”
        });
        jQuery(“#ValidDate”).validate({
        expression: “if (!isValidDate(parseInt(VAL.split(‘-’)[2]), parseInt(VAL.split(‘-’)[0]), parseInt(VAL.split(‘-’)[1]))) return false; else return true;”,
        message: “Please enter a valid Date”
        });
        jQuery(“#ValidEmail”).validate({
        expression: “if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;”,
        message: “Please enter a valid Email ID”
        });
        jQuery(“#ValidSelection”).validate({
        expression: “if (VAL != ‘0′) return true; else return false;”,
        message: “Please make a selection”
        });
        jQuery(“#ValidMultiSelection”).validate({
        expression: “if (VAL) return true; else return false;”,
        message: “Please make a selection”
        });
        jQuery(“#ValidRadio”).validate({
        expression: “if (isChecked(SelfID)) return true; else return false;”,
        message: “Please select a radio button”
        });
        jQuery(“#ValidCheckbox”).validate({
        expression: “if (isChecked(SelfID)) return true; else return false;”,
        message: “Please check atleast one checkbox”
        });

        jQuery(“#contactform”).submit(function(){
        jQuery.post(‘post.php’, jQuery(“#contactform”).serialize(), function(data){ jQuery(“#contactform”).html(data); });
        return false;
        });
        });

        Sorry for posting all this, but am just trying to figure this out you know.:-)

        Cordially
        Vayu

        • GeekTantra says:

          Hi,

          Actually I tried the exact same script and was able to get it working.
          Please check it out again seems you are making some minor mistakes.

          GeekTantra

          • Vayu says:

            Hi GeekTantra.

            Okay, thats weird! Its not working for me and all have done to your advanced_demo is add an ID to the form called #contactform, created a post.php file and added the submit code below the validation code.

            I must admit, that I can’t see what should prevent it from running the submit code either.

            Its a shame, because I like your validation code…

            Thanks for all your help on this. I really appreciate your time. :-)

            Vayu

  4. GeekTantra says:

    Hi vayu,

    Please send in your email id in the next comment so that I can modify the source code for the advanced demo and send it to you.

    GeekTantra

  5. Alex M says:

    Hey, this is an awesomely clean and simple real-time validation tool. I was wondering if you could tell me how to replace the submit button with “back” and “next” buttons?

  6. Slaver says:

    There is a problem with ajax-submission. For example, in advanced demo we can replace default code by such:

    jQuery('.AdvancedForm').validated(function(){
    jQuery('.AdvancedForm').submit(function(){
    jQuery.post(jQuery(this).attr('action'), jQuery(".AdvancedForm").serialize(), function(data){
    jQuery("#ajaxerror").hide('slow');
    $(".Tabs").append( '' + String((new Date()).getTime()).replace(/\D/gi,'') + '' );
    });
    return false;
    });
    });

    1. First click or enter (submit) doesn’t work
    2. After second submission, form would be submitted twice, after third – thrice etc.

    How to solve this problem?

  7. Slaver says:

    Instead of:
    $(".Tabs").append( '' + String((new Date()).getTime()).replace(/\D/gi,'') + '' );
    should be:
    $(".Tabs").append( '' + String((new Date()).getTime()).replace(/\D/gi,'') + '' );

  8. zeev says:

    10x, great plugin :)

    i have one question thu…

    how can i require at least one field in a group to b filled ?

    • GeekTantra says:

      Hi zeev,

      Thanks for the appreciation. You should check out the advanced demo of the Live Validation plugin, you can find a checkbox validation there which I guess is a similar case which you require. In the checkbox validation at-least on checkbox should be checked in the whole group of checkboxes for the validation to be correct.

      Regards,
      GeekTantra

  9. GDP says:

    Than you for a very well done script. I have one question. I need to validate saveral items in the same form with the ValidField option. Since the script validates by id of the form (the id of each element of the form must ne unique), does that mean I have to repeat the query over and over ?
    Let me explain. I have an element with id=ValidFirstname and another one with id=ValidLastname. Do I need two JQuery functions ? one

    jQuery(“#ValidFirstname”).validate

    and another

    jQuery(“#ValidLastname”).validate

    In other words, how dow I use jQuery(“#ValidField”).validate to test two different fields with different element id in the same form ?

    Thank you for your time !!!

  10. YOUR-TITLE says:

    jQuery Live Form Validation | GeekTantra…

    Thank you for submitting this cool story – Trackback from YOUR-TITLE…

  11. Paul says:

    Hi,

    I can see that the demo fires the validation if the user presses the Submit button. How can I get the validation to fire from a Template Based Button. i.e. My button does not have a type of Submit. It looks like this :-

    Submit

    Hope that makes sense :o )

    Regards

    Paul

  12. Paul says:

    Hi,

    I can see that the demo fires the validation if the user presses the Submit button. How can I get the validation to fire from a Template Based Button. i.e. My button does not have a type of Submit. It looks like this :-

    [code]

    Submit
    [/code]

    Hope that makes sense :o )

    Regards

    Paul

  13. Paul says:

    Hi,

    Third Try to paste my HTML!!!!!

    I can see that the demo fires the validation if the user presses the Submit button. How can I get the validation to fire from a Template Based Button. i.e. My button does not have a type of Submit. It looks like this :-

    Submit

    Hope that makes sense :o )

    Regards

    Paul
    Reply

  14. Paul says:

    Hi,

    Last Go !!!!!

    I can see that the demo fires the validation if the user presses the Submit button. How can I get the validation to fire from a Template Based Button. i.e. My button does not have a type of Submit. It looks like this :-

    a id=”17988421045816501″ class=”jq-button ui-state-default ui-corner-all” href=”javascript:doSubmit(‘SUBMIT’)”>Submit /a

    Hope that makes sense :o )

    Regards

    Paul

    • GeekTantra says:

      Hi Paul,

      I got your problem. You can easily do this by creating a link like as follows
      <a href=”javascript:void(0)” onclick=”$(‘#FormID’).submit()”>Submit</a>

  15. sean fullman says:

    Can you help me with conditional field validation. If the value of field 1 = True then I need to validate field 2 otherwise I do not validate field 2.

  16. Wouter says:

    Hi,

    I’m working on a form and using your script, which I like a lot. I have one additional wish: is it possible/easy to show a message (or an image) when the validation result is true? It would be nice to give some visual feedback when a field is filled in correctly.

    best,
    Wouter

    • GeekTantra says:

      Hi Wouter,

      It is possible. You have to manipulate the expression part call. Here before return true; put your code for any sort of visual feedback script.

      Regards,
      GeekTantra

  17. Mask says:

    Hi,geektantra! I’m using your validation plugin and found some problems here:
    1.when we are validate a email, if the invalid email is too long(I tested if over 27 charecters), the js’s efficiency will down sharply , and this caused many browser’s stop on it except safari

    2. when the param live set to false, when I input three invalid field and start to correct one by one, I can’t know whether I corrected it,because they will stay wrong status untill they are all correct.

    hope you got it , and looking forward your reply!

  18. Jelle says:

    Hello,

    I am new in Javascript, and i have a question.
    I have tried some things, but it won’t work.

    Is it possible to check if a field has a value between 2 numbers?

    Greetz,

    Jelle

  19. tyler says:

    Excellent validation plugin! It’s so simple to implement compared to many of the other plugins available.

  20. Kane says:

    Great Plug In. I would like to add a PHP random math captcha generator, with this code:

    but Im having syntax issues on the validation expression, could you help? here is what Im trying to use
    $(“#math”).validate({
    expression: “if (VAL = ()) return true: else return false;”,
    //if (VAL > 100) return true; else return false;
    message: “You are stupid”
    });

  21. Sean says:

    Hi,

    Excellent script. Thanks so much. I’ve run into an issue with the email validation. My Domain name has a “-” dash in the anme, and when I input this it says “invalid email address”. Is there a modification I can make to the code so that the email validation accepts “-” dashes?

    • GeekTantra says:

      just add – to the regex like:

      jQuery(“#ValidEmail”).validate({
      expression: “if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;”,
      message: “Please enter a valid Email ID”
      });
      It should work fine.

  22. Sean says:

    Hi,

    Thank you for the code but its still coming up as invalid. I am just going to validate it as regular text. Is there any way to execute a javascript alert box if errors are present? (problem is this form on my page is very long and users might not see an error at the top of the page)

    Thank you for your help.

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes