Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate plug in - validating hidden elements only when visible

I have a form that has a "Is you billing address the same as your shipping address" field. If the user clicks the radio button "No" the hidden ul#billingAddress is shown. The fields contained in ul#billingAddress are required if it is visible, that is if the ul has display:block.

How do I write a custom addMethod for jquery validate.js that requires those only if the field is visible? This is what I have that isn't working.

$.validator.addMethod ("BillingSameAsShipping", function(value, element) {
   var billingFields = ['billingAddress1','billingAddress2','billingCity','billingState','bilingZip']
   if ($("#billingAddress").is('visible') && billingFields.val('') {
       return false;
   } else 
       return true;
 }, "Please fill in the required billing information" );

This, obviously is jacked. I need to make it work for each one that is in the var.

Thanks!

like image 218
Dirty Bird Design Avatar asked Aug 15 '10 21:08

Dirty Bird Design


1 Answers

The problem with the visible check is this part: .is('visible') it needs to be: .is(':visible') to use the :visible selector.


As an alternative, you can use the ignore option to do what you want a bit easier, like this:

$("#myForm").validate({
  //other options
  ignore: ':hidden'
});

This approach lets you use the standard required rules if you want.

like image 174
Nick Craver Avatar answered Oct 24 '22 03:10

Nick Craver