Sunday, October 9, 2011

JQuery - validate plugin for dependency validation (i.e. fields required if 1 has value))

This code will give you an option to make some fields required if a source field has some value. If the source field has no value, then other fields are not required. You can also have the option to equire all dependencies or at least one of them have a value.
function validateDependency(sourceClassname, dependentClassname, message, requireAll) {
jQuery.validator.addMethod(sourceClassname, function (val, el) {
var textboxes = $(':input:text[class^="' + sourceClassname + '"]:filled').length;
var checkboxes = $(':input:checkbox[class^="' + sourceClassname + '"]:checked').length;
var radios = $(':input:radio[class^="' + sourceClassname + '"]:checked').length;
if (textboxes || checkboxes || radios) {
textboxes = $(':input:text[class^="' + dependentClassname + '"]:filled').length;
checkboxes = $(':input:checkbox[class^="' + dependentClassname + '"]:checked').length;
radios = $(':input:radio[class^="' + dependentClassname + '"]:checked').length;

if (requireAll) {
textboxes = ($(':input:text[class^="' + dependentClassname + '"]').length == textboxes);
checkboxes = ($(':input:checkbox[class^="' + dependentClassname + '"]').length == checkboxes);
radios = ($(':input:radio[class^="' + dependentClassname + '"]').length == radios);

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

No comments:

Post a Comment