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)
This entry was posted in Javascript, Programming and tagged , , , . Bookmark the permalink.

188 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. Pingback: 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. Pingback: 16个Javascript表单事件脚本(表单验证、选择) « 幻岛|领地

  20. tyler says:

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

  21. 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”
    });

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

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

  24. Prasan says:

    Hi,

    During date validation, the error when displayed moves the date picker image to the right side. That is, a span is created(to display the error message) before the date picker img class. It looks a little odd. Anything can be done, to display the error message after the date picker(without disturbing it) ?

    Thanks in advance.

    Prasan.

    • tomas says:

      i had the same problem and my work around was to modify the jquery.validate.js. Where you get these lines:

      var self = jQuery(id).attr(“id”);

      … more lines of code …

      if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {
      jQuery(id).after(” + options['message'] + ”);
      jQuery(id).addClass(options['error_field_class']);

      you can first check for a particular “id” in your form, in my case the id of an inmediately to the left of the date picker img. If the self variable matches one of those ‘s id(i got many in the same form), you can add this inside the ‘ style=”position: absolute; left:’ + someExpression + ‘px; top=:’ someExpression2 + ‘px;” … >. Where someExpression and SomeExpression2 can be the LEFT position + offset, the top attribute respectively.

      You end up having something like this:

      if (self == ‘id of a particular input’) {
      if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {
      jQuery(id).after(”
      options['message'] + ”);
      jQuery(id).addClass(options['error_field_class']);
      } else {
      if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {
      jQuery(id).after(”
      options['message'] + ”);
      jQuery(id).addClass(options['error_field_class']);
      }

      Sry for the long post, but it was quite hard to explain and make it somewhat understandable.

      • tomas says:

        damn, something happened with the code and everything was auto-deleted.

        okay short answer: before this line if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {

        add an if comparing the variable “self” with your ‘s id that is near to the date picker. If it’s true, add into the span a style, with absolute position, left and top of your choice until it aligns fine in your page. If its false, just leave the orinal span without the style.

        • Prasan says:

          Hey Tomas,

          Thanks for your reply. Kindly let me know in which line I should add the span tag containing the left, top. It would be helpful if you wish, could paste your code from jquery.validate.js

          Thanks.

          • Prasan says:

            Tomas,

            I got it. Is there any other work-around to this problem, since I am not inclined to using absolute value.

            TIA

            • tomas says:

              hmm i don’t know if it will work, but the idea is basically checking if the variable self matches the input located to the left of the calendar date picker, and if so doing a jquery(#calendar_id).after( span code here…). That will add the red text to the right of the calendar, although it may be too close to it, or worst don’t work at all, anyway if it works and it’s too close, you could add a style attribute to the span with padding-left.

              The code should be like this more or less (i will change open and close html tag symbols with &lt and &gt respectively because i can’t figure out how to display them in this blog). If by doing that they display correctly, well bite me xD.
              add it inside the “if (!validation_state)” part of the jquery.validate.js

              if (self == ‘input_to_the_left_of_calendar_id’) {
              if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {
              jQuery(#you_calendar_id).after(‘&lt span class=”‘ + options['error_class']
              + ‘” &gt ‘ + options['message'] + ‘&lt /span &gt’);
              jQuery(id).addClass(options['error_field_class']);
              }
              } else { // this part was the original code
              if (jQuery(id).next(‘.’ + options['error_class']).length == 0) {
              jQuery(id).after(‘&lt span class=”‘ + options['error_class'] + ‘” &gt ‘ +
              options['message'] + ‘&lt /span &gt’);
              jQuery(id).addClass(options['error_field_class']);
              }
              }

              if some of the code above went missing, i give up posting code in this blog lol, to resume, the idea is to make a jquery(#calendar_id).after( span ) if variable self matches the input’s id to the left of the calendar img.

              Hope that helps!

  25. Prakaaah says:

    I got error during date validation in your Advanced Demo page. Ex: 03/09/2010

    • tomas says:

      its a parseInt bug,
      change expression: “if (!isValidDate(parseInt(VAL.split(‘-’)[2]), parseInt(VAL.split(‘-’)[0]), parseInt(VAL.split(‘-’)[1]))) return false;

      to expression: “if (!isValidDate(parseInt(VAL.split(‘-’)[2], 10), parseInt(VAL.split(‘-’)[0], 10), parseInt(VAL.split(‘-’)[1], 10))) return false;

      that forces parseInt to use a 10-base if there’s a 0 as the first number like 03. Without that “,10″, it uses octal base, which wrecks everything :P

  26. Tod Cott says:

    This is a impressive blog, im delighted I discovered this. Ill be back again later to check out other posts that you have on your blog.

  27. Pingback: 6 plugins to do inline form validation with jQuery - spiced2.com

  28. I am new to blogging, so I feel like I am in the “just taking notes” phase. But when I do find a blog topic I like, I do comment because I genuinely like what has been said or the information was helpful to me. I am officially linked to your blog now, so I will be checking in often! Thanks for all the great advice.

  29. Emily says:

    Hi,

    I was wondering if there is a response to Mask’s question:

    Mask says:
    December 29, 2009 at 10:35 am

    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.

    • Emily says:

      ooops… submitted that before I’d finished! Is there a way round this because it is a bit confusing… I’m currently working on new web forms and I know the second they go into testing I’m going to be asked to fix this.

      Thanks for your help… love the plug in by the way, really easy to implement!

  30. pradeep jangir says:

    validation for checkbox selection

  31. tomas says:

    BUG: Click a text input box, press tab or click on another one so that the red message error appears right next to the first one. Now VERY FAST click the first input box again and press tab IMMEDIATELY just before the red text fades out completely. Doing that causes the red text not to show again, when it should because the input is empty.

    Note: Pressing the submit button will display again the error message, but it’s confusing to the user anyway.

  32. Pingback: 30 个最好的jQuery表单插件 - Cc'S BloG

  33. Pingback: 30 个最好的jQuery表单插件  -  jQuery插件开源软件

  34. Pingback: 30个最好的jQuery表单插件 - 易维动感品牌设计中心

  35. Pingback: 30 个最好的jQuery表单插件

  36. Pingback: BEST AJAX EXAMPLES - Nagpur

  37. 123doing says:

    It’s very good.
    I like this.
    Thanks for share.
    And I wrote something to introduce this project for my readers.
    You can find the post about this in my website.
    If something is wrong,pls figure it out.thanks.

  38. Pingback: jQuery Live Form Validation 开源项目 - Ajax代码大全 - Java开源项目 - 表单Form - ajax表单form控件 - Java免费软件 - jQuery-Live-Form-Validation - 开源网

  39. Pingback: Formularvalidierung in Echtzeit für zufrieden User | grafixx.at

  40. Pingback: 50 jQuery Plugins for Form Functionality, Validation, Security and Customisation - Speckyboy Design Magazine

  41. Pingback: 50 jQuery Plugins for Form Functionality, Validation, Security and CustomisationUjwal's blogs | Ujwal's blogs

  42. Manivannan says:

    Hi,

    I have tried this plugin in my rails project.
    Its very fine and easy to use.. Nice..I got two problem.

    1) i want to disable submit button after submission of form
    if i submit with error , button become disabled, how to enable submit button ?

    2) When i submit normal form, validation is working fine, but got problem with ajax form.

    Disable submit button code:
    $(‘form’).submit(function(){
    $(‘input[type=submit]‘, this).attr(‘disabled’, ‘disabled’).val(“Submiting…”);
    $(‘select’, this).attr(‘disabled’, ‘disabled’);
    $(‘input[type=text]‘, this).attr(‘readonly’, ‘readonly’);
    $(‘textarea’, this).attr(‘readonly’, ‘readonly’);
    });

    Ajax form Code:

    {:action=>”create”},:html=>{:id=>:forgot_password_form},
    :loading => update_page do |page| page.show “loader” end,
    :complete => update_page do |page| page.hide “loader” end) do |f| %>

    loading…

    jQuery(function(){
    jQuery(“#user_email”).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: “Should be a valid Email”
    });

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

  43. getafriend says:

    How to check whether username already exist in database or not through ajax call ?

    Please help.

    Best Regards,
    GetAFriend

    • GeekTantra says:

      You have to write the AJAX query to check the username inside the validation string.

      • GeekTantra says:

        function check_if_username_exists(username) {
        var username_available = false;
        jQuery.get(‘http://url.to.your.query’, { ‘username’: username }, function(data){
        if(data ==’success’ ) {
        username_available = true;
        }else{
        username_available = false;
        }
        });
        return username_available;
        }

        jQuery(function(){
        jQuery(“#“).validate({
        expression: “if ( check_if_username_exists(VAL) ) return true; else return false;”,
        message: “Username already exists”
        });
        });

  44. Pingback: 入力フォームに関するjQueryプラグインまとめ | Blitz

  45. Nathan says:

    I had a quick question, This form doesnt seem to be link to a php form when you press the submit button. Can someone tell me how I could make the form send out and working?

  46. ettore says:

    hi how i can make a remote validate???????

    for exemple a username check from a check.php page????? Its possible?

    • GeekTantra says:

      function check_if_username_exists(username) {
      var username_available = false;
      jQuery.get(‘http://url.to.your.query/check.php’, { ‘username’: username }, function(data){
      if(data ==’success’ ) {
      username_available = true;
      }else{
      username_available = false;
      }
      });
      return username_available;
      }
      jQuery(function(){
      jQuery(“#“).validate({
      expression: “if ( check_if_username_exists(VAL) ) return true; else return false;”,
      message: “Username already exists”
      });
      });

      use the above code…

  47. Nathan says:

    Can someone tell me how I can make the form send. Like what do I need in a php file so I can send it out with this form. If someone can help me out now I would really appreciate that.

    • GeekTantra says:

      The form is like a standard form with front-end validation enabled. When all the validations pass it will automatically post the form data to the action file.

      You can use standard $_POST of php to fetch variables from the form.

      • Nathan says:

        I tried adding a normal $_POST php file to the form but it didnt seem to work. When I download the form it did not have a action file I had to add one my own php file to the action but it didnt even work.

  48. Solomon says:

    Is it possible to modify this code to check at least one text box is filled. I have three phone number and I need only one of them has text inside.

    Thanks,

  49. KristianT says:

    You need to add a check to see if the field is blank on your blur event. It doesn’t seem correct that you click on a field, then click on another field and the previous one goes red even though I have not yet attempted to fill in the field.
    So currently if you simply click on the fields from top to bottom without entering anything they will all go red, even if you don’t enter anything.

    • GeekTantra says:

      Hi Kristian,

      The activation of the validation is on the blur event only. You can try the validation without the mouse only using the “Tabs” on the keyboard. The fact that all fields go red when you click on submit is because they are all required.

      Do get back in-case you have any more doubts.

      Regards,
      GeekTantra

Leave a Reply

Your email address will not be published. Required fields are marked *