I am using jQuery with the Validate Plugin and Nathan Long's awesome method require_from_group unfortunately I'm encountering a problem with validating other fields inside the form.
Anything above the set of required fields is not having it's error messages displayed properly.
This (plus jQuery 1.4.2 and Validate Plugin) is my code:
<form>
<label for="fullName">Name <em>required</em></label>
<input id="fullName" name="fullName" type="text" class="required"><br />
<fieldset>
<legend>Enter 1 of 3 emails <em> required</em></legend>
<label for="field1">field1</label><input id="field1" class="group_required email" type="text" name="field1" /><br />
<label for="field2">field2</label><input id="field2" class="group_required email" type="text" name="field2" /><br />
<label for="field3">field3</label><input id="field3" class="group_required email" type="text" name="field3" /><br />
</fieldset>
<input name="submitbutton" type="submit" />
</form>
<script>
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
numberRequired = options[0];
selector = options[1];
//Look for our selector within the parent form
var validOrNot = $(selector, element.form).filter(function() {
// Each field is kept if it has a value
return $(this).val();
// Set to true if there are enough, else to false
}).length >= numberRequired;
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
//.valid() means "validate using all applicable rules" (which
//includes this one)
fields.data('being_validated', true).valid();
fields.data('being_validated', false);
}
return validOrNot;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
$(document).ready(function(){
$("form").validate({
debug: true,
});
jQuery.validator.addClassRules("group_required", {require_from_group: [1, ".group_required"]});
});
</script>
The actual page is more complicated but this is all the code you need to replicate the problem. Submit the form without filling in any fields and you will see an error message next to the 3 in the group but not the name field. If the name field is in the HTML after the fieldset validation on it works fine. Giving the name field focus and then blur does produce the correct error message but it's not appearing on submit.
I have seen another of others with this problem in the comments on the original question but did not see any responses :(
Commenting out:
fields.data('being_validated', true).valid();
fixes the error message display problem but re-introduces the problems that Nathan was trying to solve.