Sunday, October 9, 2011

JQuery - validate plugin for group validation (i.e. at least 1 required field)


Here's how to validate group using JQuery's Validate Plugin. You must add your own method for the group validation.

function validateGroup(classname, message) {
jQuery.validator.addMethod(classname, function (val, el) {
var textboxes = $(':input:text[class^="' + classname + '"]:filled').length;
var checkboxes = $(':input:checkbox[class^="' + classname + '"]:checked').length;
var radios = $(':input:radio[class^="' + classname + '"]:checked').length;

return textboxes || checkboxes || radios;
}, (message != null ? message : 'Please fill out at least one of these fields'));
}


With the group validation, JQuery will display several error messages for a group of textboxes. It is so annoying becaue I only wanted to display 1 error message for the whole group rather than on each field. Since I haven't found yet the solution on how to do that using the JQuery plugin, I override the "invalidHandler" function for the plugin. Here's what I did.

function validateForm(formname,errorContainer) {
jQuery.validator.messages.required = "You missed some required fields.";
var formObject;
if (formname)
formObject = $("#" + formname);
else
formObject = $('input[name="submitButton"]').closest("form");

formObject.validate({
errorClass: "invalid",
highlight: function (element, errorClass) {
$(element).addClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.addClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass);
$(element.form).find("label[for=" + element.id + "]")
.removeClass(errorClass);
},
errorContainer: "#" + errorContainer,
errorLabelContainer: "#" + errorContainer + " ul",
wrapper: "li",
errorElement: "span",
invalidHandler: function (form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
message = "" + message + "

    "; var errorListing = new Array(); $.each(validator.errorList, function (index, value) { if ($.inArray(value.message, errorListing) < 0) {
    errorListing.push(value.message);
    message += "
  • " + value.message + "

  • "; } }); message += "
";
ScreenManager.Error(null,message);
} else {
//$("div.error").hide();
}
}

});
}

Here's a sample usage of the script:



If somebody knew a better approach to this, please let me know.

No comments:

Post a Comment