Monday, June 28, 2010

jQuery Validate: Required If Visible

I needed a generic "required if visible" rule for use with the jQuery Validation plugin. This is the result:

// jQuery.validate.requiredIfVisible.js
// Copyright (c) 2010 Ori Peleg,, distributed under the MIT license
(function($) {
function(value, element, params) {
function isVisible(e) {
// the element and all of its parents must be :visible
// inspiration:
return":visible") && e.parents(":not(:visible)").length == 0;

if (isVisible($(element))) {
// call the "required" method
return $, $.trim(element.value), element);

return true;


  • Using required:"#myinput:visible" could have worked, but ":visible" doesn't check for hidden parents, and I didn't want to repeat the element selector.
  • ":hidden" is false for elements with the "visibility:hidden" CSS rule, so I couldn't use ":not(:hidden)" either.
  • Technique for checking element visibility from Remy Sharp's blog.