2
votes

The valid() function states: "Checks whether the selected form is valid or whether all selected elements are valid."

Which seems to imply we can test for a group of controls using a selector (we're testing controls on a asp.net form) e.g.

$('div[id$=pnlBillingInfo] .Field input').valid()

This works if all fields are required. However, if one field requires no validation (required = false) then valid() returns false when this field is left blank.

This behavior doesn't seem correct - are we missing something? We should be able to leave these optional fields blank and still have the group of controls validate ok.

If we try to validate this optional field - the result is 'undefined' e.g.

$("#aspnetForm").validate().element('input[id$=txtBillingAddress2]')

jQuery 1.4.2

jQuery plugin Validation 1.7 (latest version)

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Thanks!

2
Note that validate() is being called before checking for valid() e.g. $('#aspnetForm').validate(); $('div[id$=pnlBillingInfo] .Field input').valid() - Matt
The result will be undefined if there are no rules, that's the expected behavior, does this field have any rules? - Nick Craver
There is a rule defined (required = false). It would still make sense that validate().element returns undefined since there's nothing to validate. However, the real puzzle is why valid() returns false. - Matt
A work around for this issue is creating a function that loops through each field in the selection and checks if each field is valid or not. - Matt

2 Answers

1
votes

I've found it useful to actually separate the form validation rules from the validation event (ie: the moment when the form is submitted).

You need to set up rules for the form - either in the JS or in the HTML via classes on each input / select / etc.

I prefer doing it via JS, because it keeps the DOM clean; also, I usually put the form's rules outside the $(document).ready() function:

$('#form').validate({
    rules: {
        [...]
    },
    messages: {
        [...]
    }
});

This actually does nothing functional. It just sets the rules. When you need to actually validate the form, you can check these rules by firing the .valid() event:

$(document).ready(function(){
    $('#form').submit(function(){

            // Check validity
            if (!$(this).valid()) return false;

            // Form is valid, so submit it!
            [...]
    });
});
1
votes

There's a bug on the library when rule methods check for optional fields with "this.optional(element)". When the field is empty this.optional returns "dependency-mismatch" and the validation method returns "undefined" marking the field as invalid.

Full explanation here:

https://github.com/jzaefferer/jquery-validation/issues/481