jQuery plugin: Validation

Current version: 1.6
Compressed filesize: 14.344 bytes
License: MIT/GPL

Files:

Download
Changelog
Demos
Documentation

On Microsoft’s Ajax CDN (hotlinking welcome):

Dependencies

Required

Optional

Support

  • Please post questions to the jQuery discussion list, putting “(validate)” into the subject of your post, making it easier to spot it and respond quickly. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the plugins.jQuery.com bug tracker (requires registration).

Donate

$ USDDonate€ EURDonate

572 Responses to “jQuery plugin: Validation”

  1. Yann says:

    I found the problem.

    my form had a name but no id :)

  2. Andreas R says:

    Hi! The demo on the jquery wiki doesn’t seem to work (firefox, opera). No errors, and no validation.

    Also, I can’t seem to get it working myself either :)

  3. Mark M says:

    Hi – I’ve scoured the pages and docs, so hopefully this isn’t a very obvious. I’m pretty new to jQuery unfortunately – it, and this plugin is very cool though.

    I simply want to enable or disable a submit button based on whether a form is currently valid.

    I can currently disable the submit button if there are form errors:

    $("#cmxform").validate({
    showErrors: function(errorMap, errorList) {
    disableSubmitButton();
    this.defaultShowErrors();
    }
    });

    But i can’t work out a callback name which will enable the submit button if the form appears valid at the current time.

    Any help appreciated.

    /Mark

  4. mykle says:

    Hello Jörn,

    This looks like a very nice plugin, but it took me a few hours to figure out that it depends on jQuery 1.2, which means that Drupal users such as myself can’t use it. (The current Drupal release (5) officially supports only v1.0, but some people have hacked it up to v1.1.)

    The problem is that jquery.validate calls jquery.metadata which calls jquery.data(), added in jq1.2 . Can you suggest a workaround for this?

    Version management seems to be a bit messy in jQuery land; I’d propose that plugin authors number their modules to match the jQuery version they depend on … so your 1.1 version could be 1.2.1, the next one 1.2.2, etc. But there may be a better way.

    Thanks,
    -mykle-

  5. Vishal says:

    Hello Jörn,

    Is there any way to add animation effect on error messages. I am able to add effect on success messages by implementing the success function i.e


    success: function(label) {
    // set   as text for IE
    label.html(" Ok!").fadeIn("slow");
    }

    but not sure how should i implement it for invalid input messages. I want to implement this animation on blur event only. Can you please suggest any possible way??

  6. chadi says:

    Hello,

    Nice plugin!
    I have a problem when using ajax to alter the document. Any feedback would be appreciated.

    I have a php page with many tabs. On intial loading, a designated section of the page is empty (div). When you click on a tab, it loads a with fields…etc using ajax in that empty div. This form has validation rules but it does not work; as I understand, because the jQuery validation needs to be reinitialized.

    1) Can you give me an example of how to handle reinit of dom in this situation?

    2) also since the intial loading of the page does NOT contain any forms, the page generates a JS error – because validation is present in but no form is present.

    Thanks again!

  7. Adisonz says:

    I have removed some element on the page and added how element, how to make the newly added element to work with the validation plugin ?

  8. Jamie Jensen says:

    Hello Jörn,

    I finally started to get some results from the validation. It took me a while because I was using the wrong versions of jquery.js and jquery.validate.js together.

    My question is this;
    How would I return 2 separate types of error message in the same form.

    My form is made up of both tables and a tableless div layout. I have 3 radio buttons that need to be validated in the table and I am unable to get an error message to appear. I want only the error message for the table radio buttons to appear in the error container. All other error messages would appear near their respective input field.

    My though was to use an error container under the table for the radio buttons, however I am unable to make that work either.

    The form is at http://www.mailhost123.com/work/order_he_jscript.htm

    Thank you,

    Jamie Jensen

  9. Felix says:

    Hallo Jörn,

    sehr schönes Plugin.

    Weiter in Englisch:

    I’ve tested your plugin, it works very well.
    The only two things I don’t get solved are

    - The remote function. Isn’t it stable yet or do you have already a solution?
    - I don’t get it working to submit the form via AJAX. I’ve searched the net, but I never found a solution. Also your Script example isn’t working for me.

    Could you give me some help? Thanks in advance.

    Viele Grüße
    Felix

  10. Peter says:

    Hi Jörn,

    first of all congrats to such a nice plugin!

    Regarding the error of Yann (20. Dezember 2007 |16:55):
    I also got the same error.

    I found out it was due to some shared JS-code on two pages which called $(…).validate().
    One page had the right form-id in it, in the other (test)-page, the id was different.

    As to my understanging, calling functions on empty jquery-objects should not result in an error, so:
    $("#n_a").size();
    is just fine.

    However, calling:
    $("#n_a").validate(…);
    results in the error
    elem has no properties

    This is because this[0] is directly accessed in jQuery.fn.validate.

    Putting the following line on top:
    if (!this[0]) return;
    (or something like that) does the trick.

    Best regards,
    Peter

  11. Jamie Jensen says:

    Hello Jörn,

    I have 2 issues that I will address with 2 posts. My first is custom error placement. I have 2 different radio button groups that I wish to have the error displayed somewhere other than the bulk of error labels.

    I was able to use the if…else statement found in one of the demos to specify where the error was placed. The shortcoming to this is that only one of those works. I need two error messages in different locations for the radio groups.

    Thoughts?

    You can see the page, errors and source at http://www.mailhost123.com/work/order_he_broken.htm

    Thanks,

    Jamie Jensen

  12. Jamie Jensen says:

    My second question is completely hidden from me.

    I have a section that is hidden on my form unless a radio button is selected.

    If the button is selected and the fieldset is then visible the fields are required. If not, don’t bother with them.

    I am also trying to use an if…else statement here but I get errors that I am unable to understand.

    I have also just tried to use …
    required: function() {
    return ($j('#billing_cc').css('display') != 'none');
    },

    … but the ‘error’ label still gets applied and the form is not submitted.

    What am I doing wrong? (besides trying to act like I can program…)

    Thanks,

    Jamie Jensen

  13. Jamie Jensen says:

    ok, so maybe I am just lazy and not stupid? I’ll leave that to the reader to decide.

    The validation problem in my second question was caused by improper placement of the function? The required portion of the validation process.

    I had …
    cc_state: {
    required: function() {
    return ($j('div#billing_cc').css('display') != 'none');
    }
    required: function() {
    return $j("#cc_state").val() !== 'Select a State';
    }
    },

    Which cause the required component of the field to always be checked.

    I changed it to …
    cc_state: {
    required: function() {
    return ($j('div#billing_cc').css('display') != 'none');
    }
    required: function() {
    return $j("#cc_state").val() !== 'Select a State';
    }
    },

    and it worked properly.

    I am checking 9 fields, is there a better way to make my code block a bit smalled and more efficient?

    Thanks,

    Jamie Jensen

  14. Jamie Jensen says:

    err… proving my point ? *shrugs*

    original…
    <code>cc_state: {
    required: function() {
    return ($j(‘div#billing_cc’).css(‘display’) != ‘none’);{
    required: function() {
    return $j(“#cc_state”).val() !== ‘Select a State’;
    }
    },</code>

    changed and working …

    <code>cc_state: {
    required: function() {
    return ($j(‘div#billing_cc’).css(‘display’) != ‘none’); {
    required: function() {
    return $j(“#cc_state”).val() !== ‘Select a State’;
    }
    }
    }
    },</code>

  15. Leigh Dodds says:

    Hi,

    I’m trying to work out how to apply validation to a form that allows users to dynamically add and remove elements. To achieve this I’m just using the JQuery clone method.

    The fields added to the form are “required”, but the validation doesn’t seem to want to apply to the newly added fields. In fact it seems to be validating the originally cloned field instead.

    Looking at the comments on this page I think I need to be using the refresh() method but this isn’t documented, and seems to have been removed from the most recent code: the dynamic totals example doesn’t seem to use it either.

    Is there some documentation or a simple example of this somewhere?

  16. SubOne says:

    I am trying to use this plugin with a control array, but I can’t seem to get it working. The way I have it setup is something like:


    <form id="reg1Form" class="pretty" method="post" action="">
    <fieldset id="badge">
    <legend>Your Registration Information</legend>
    <ol>
    <li>
    <label for="register_name[]" class="required">Full Name:</label>
    <input type="text" name="register_name[]" class="medium" maxlength="32" />
    <span class="tip">First then last (e.g. John Doe)</span>
    </li>
    </ol>
    </fieldset>
    <input type="button" id="register_add_guest" name="register_add_guest" onclick="addGuest();" class="addguest" value="Add Guest">
    <input type="submit" name="register_submit" class="nextstep" value="Next Step">
    </form>

    Now validation works fine at this point until I click “Add Guest”, which closes the “badge” fieldset and inserts it before the buttons. After the clone I have this in the code:


    <form id="reg1Form" class="pretty" method="post" action="">
    <fieldset id="badge">
    <legend>Your Registration Information</legend>
    <ol>
    <li>
    <label for="register_name[]" class="required">Full Name:</label>
    <input type="text" name="register_name[]" class="medium" maxlength="32" />
    <span class="tip">First then last (e.g. John Doe)</span>
    </li>
    </ol>
    </fieldset>
    <fieldset id="badge1">
    <legend>Guest #1 Registration Information</legend>
    <ol>
    <li>
    <label for="register_name[]" class="required">Full Name:</label>
    <input type="text" name="register_name[]" class="medium" maxlength="32" />
    <span class="tip">First then last (e.g. John Doe)</span>
    </li>
    </ol>
    </fieldset>
    <input type="button" id="register_add_guest" name="register_add_guest" onclick="addGuest();" class="addguest" value="Add Guest">
    <input type="submit" name="register_submit" class="nextstep" value="Next Step">
    </form>

    But now the first fieldset is the only one being validated. The user can click “Add Guest” as many times as they want as well as remove individual fieldsets if they decide they no longer need them. However, I can’t get the form to validate the dynamically added fields.

    Any help with this would be greatly appreciated.

  17. hi,
    I just got ajax validation to work on our site using the latest FC1 of jquery.validate(). Brilliant stuff!

    I’ve run into two glitches this far:

    1) Every now and then the form submit button won’t work although all fields in the form are valid, this happens a lot when I use ajax fields (that check for unique email/username, etc).

    2) I’ve tried to make small script for highlighting fields (displaying a checkbox mark as user feedback) for valid fields. It looks something like this:

    var username = $(“#user_username”);
    username.blur(function(){
    if (validator.element(username)) {
    username.addClass(‘valid’);
    }
    });

    Unfortunately the validator.element function returns undefined every now and then, so I cannot really use this. Is there another way of doing this? What I basically want to do is assign a “valid” class on blur to form fields that are valid.

    Here’s my form code:
    http://pastie.caboo.se/140481

    Thanks for a great plugin! // eric

  18. Hi again,
    regarding 2) above this only fails on fields that are checked with ajax.

    cheers // eric

  19. SubOne says:

    That last post reminds me I made an edit to your code:

    if ( !this.depend(param, element) )
    changed to:
    if ( !this.depend || !this.depend(param, element) )

    I was getting an error that this.depend was not a function and it was making the rest of the validation fail.

  20. Yuval says:

    Hey Jörn,
    I was trying to implement the latest revision of the validation plugin but it did not work. So I followed all of the revisions and realized that my form stops working right between revisions 4325 and 4329 (meaning 4325 is the latest revision that worked for me).
    I tried doing a comparison (http://dev.jquery.com/changeset?new=4329%40trunk%2Fplugins%2Fvalidate%2Fjquery.validate.js&old=4325%40trunk%2Fplugins%2Fvalidate%2Fjquery.validate.js) between the two but no luck. What could it possibly be?
    Thank you,
    Yuval

  21. Jörn says:

    Sorry for not responding here for quite some time. The comment system just doesn’t scale for that many comments. I’ll respond to each one since my last respnd, then shut down comments here and add pointers to future support forms. Thanks!

    All answers below will assume the 1.2 release, please upgrade if you haven’t already.

    @Olin: You can manually validate a form using the valid() on the form, as long as you init the validation before that. Give this a try:

    $("#myform").validate();
    $("img.submit").click(function() {
      if ($("#myform").valid() ) {
        // do something cool when the form is valid
      }
    });

    @David: The validation 1.2 creates only a single validator for a given form, no matter how often you call validate(). That should fix the basic problem you describe.

    @Erick: You should implement your own custom method which checks for whitespace in the filename. See $.validator.addMethod for details.

    @Howa: Enhancing error messages with animations is something I’ll try to tackle in 1.3, among other issue in that area. Animations work only on block elements, so the form layout must be optimized to support animations.

    @gabe: Yes, and there is an example showing how to implement it. See the dynamic inputs example. In that case it checks that a group of field doesn’t sum up over a certain total value.

    @Laurent: Right, either customize error placement, or place the label in the form beforehand. You can hide it via CSS and the validation plugin picks it up and displays it.

    For “array notation” you need to use quotes, eg. “bla[]“: “required”.

    @zeek: 1.2 features a complete overhaul of the email method, as well as the URL method.

    @Sheldon: Displaying messages outside the form (still) isn’t supported. “Finding” error elements depends on field-names, which are only unique inside a given form. I’ll try to tackle that in 1.3.

    For displaying general messages you should use the errorContainer option of the validate method.

    @robert: There are problems with tabs, right, I haven’t yet tried to tackle them, but will in 1.3.

    @Marvin: Validating dynamic elements is very easy in 1.2, you just need to find a neat way to create the elements and add them to the form, everything else works out-of-the-box. See the dynamic inputs example.

    @palPalani: The provided date validations are not capable of doing that, you’d have to implement your own birth-date-validation. The dateJS library may be helpful for that.

    @John: Nope, title doesn’t support multiple entries. Functions in the class attribute should work as long as you escape quotes properly. class=”{bblabl:”flafl”}” won’t work. Use single quotes instead: class=”{blaba:’flfa’}”.

    @Marcos Aurélio: Please give the remote validation in 1.2 a try. Its now complete and tested.

    @Robert: The regexes for email and url are completely replaced in 1.2.

    @Andreas R: Fixed!

    @mykle: Drupal 6 includes jQuery 1.2.x, so once that is available… The validation 1.2 release doesn’t require the metadata plugin anymore for inline-rules, but requires 1.2.2+ nonetheless. Keeping compability with older version isn’t worth it from my perspective, sooner or later everyone should be able to upgrade to current jQuery versions.

    @Vishal: Doing animations only on blur isn’t possible yet. I’m going to work on better support for animations in 1.3.

    @chadi: Currently you’ve got to check for existance of the form before calling validate. As long as you call that when the form actually exists everything should work fine.

    @Adisonz: The 1.2 release contains a lot of improvements to support dynamic forms. Please give it a try.

    @Jamie Jensen: The easiest approach would be to place the designated error message element in the form and hide it via CSS. The validation plugin will look for the element and show it accordingly.

    @Felix: Remote validation is now stable. Did you take a look at the ajaxSubmit-demo?

    @Peter: True, that is a flaw in the validation plugin. That validate method breaks the usual plugin model in other aspects, too. I’m planning to fix these in the 2.0 release, which will break a lot of compability while cleaning up a lot of mistakes of the past. Until then you’ve got to make sure that the form exists before calling validate.

    @Leigh Dodds: Please give the 1.2 release a try, it contains a lot of improvements for dynamic forms. The refresh() method is gone as there is no need to call it anymore.

    @SubOne: For the validation to work you’d have to change the name of the cloned fields. I’ll try to figure out a way to validate fields with xxx[] names, as that is too common in PHP land.

    @Eric Wahlforss: The second issue is easy to resolve by using the success-option, please take a look at the docs for validate(). That’ll work for remote checks, too.

    The first issue was a bug, thanks for reporting. The fix is included in the final 1.2 release.

    @SubOne: That change looks like it supresses the symptom, but doesn’t actually fixes the issue. Could you provide some feedback about the actual issue, eg. a testpage?

  22. Jörn says:

    Comments here are now closed.

    • Please post questions to the jQuery discussion list, putting (validate) into the subject of your post, making it easier to spot it and respond quickly.
    • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the jQuery bug tracker (requires registration). Please put [validate] into the title of a ticket.