Created
June 28, 2010 16:12
-
-
Save orip/456034 to your computer and use it in GitHub Desktop.
make a field required only if it's visible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ultimately worked for me in Chrome after wrapping the 'return true;' line in an else clause:
if (isVisible($(element))) {$.validator.methods.requried.call(this, $ .trim(element.value), element);
return
} else {
return true;
}