Skip to content

Instantly share code, notes, and snippets.

@orip
Created June 28, 2010 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orip/456034 to your computer and use it in GitHub Desktop.
Save orip/456034 to your computer and use it in GitHub Desktop.
make a field required only if it's visible
// jQuery.validate.requiredIfVisible.js
// Copyright (c) 2010 Ori Peleg, http://orip.org, distributed under the MIT license
(function($) {
$.validator.addMethod(
"requiredIfVisible",
function(value, element, params) {
function isVisible(e) {
// the element and all of its parents must be :visible
// inspiration: http://remysharp.com/2008/10/17/jquery-really-visible/
return e.is(":visible") && e.parents(":not(:visible)").length == 0;
}
if (isVisible($(element))) {
// call the "required" method
return $.validator.methods.required.call(this, $.trim(element.value), element);
}
return true;
},
$.validator.messages.required
);
})(jQuery);
@jeffp
Copy link

jeffp commented Jan 5, 2011

Ultimately worked for me in Chrome after wrapping the 'return true;' line in an else clause:

if (isVisible($(element))) {
return $.validator.methods.requried.call(this, $.trim(element.value), element);
} else {
return true;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment