43

Is it possible to easily setup a conditional rule with jQuery validate,

Simply put i'm trying add some logic which says, if checkbox 'A' is ticked - then field 'A' must be completed, if checkbox 'B' completed then fields 'B1' & 'B2' must be completed.

e.g if a checkbox with the name 'paypal' is checked - then the field named 'paypal_address' must be completed.

My existing logic is as follows:

<script type="text/javascript">
$(document).ready(function () {

$('#checkout-form').validate({
    rules: {
        first_name: {
            minlength: 2,
            required: true
        },
        last_name: {
            minlength: 2,
            required: true
        },
        address_1: {
            minlength: 2,
            required: true
        },
        address_2: {
            minlength: 2,
            required: true
        },
        post_code: {
            minlength: 2,
            required: true
        },            
        email: {
            required: true,
            email: true
        },
        terms: {
          required: true,
        }
    },
    errorPlacement: function(error, element) { 
      element.addClass('error');
    },        
    highlight: function (element) {
        $(element).addClass('nonvalid')
          .closest('.form-group').removeClass('error');
    },
    success: function (element) {
        //element.addClass('valid')
          //.closest('.form-group').removeClass('error');
          element.remove('error');
    }
});

UPDATE

Using the method below from Rohit i've almost got this working perfectly.. My form has three checkboxes (only one can be selected)

  1. Paypal
  2. Bank
  3. Check/Cheque

If Paypal is checked (by default it is) then only have the 'paypal_email_address' field required, if Bank is checked then 'account_number' & 'sort_code' fields are required & finally if Cheque is checked the 'check_payable_field' is required.

// i've got this so far

$( ".paymentMethod" ).on( "click", function() {
  var payment_method = $(this).val();
  
  if (payment_method == 'paypal') {
    paypal_checked = true;
  } else if (payment_method == 'bank-transfer') {
    bank_checked = true;
    paypal_checked = false;
  } else if (payment_method == 'cheque') {
    cheque_checked = true;
    paypal_checked = false;
  }
});
Paul T.
  • 4,703
  • 11
  • 25
  • 29
Zabs
  • 13,852
  • 45
  • 173
  • 297

5 Answers5

101

jQuery Validate actually directly supports this, using dependency expressions.

All you need to do is change your validate options like this:

$('#myform').validate({
    rules: {
        fieldA: {
           required:'#checkA:checked'
        }
    }
});

That's it!

Ryley
  • 21,046
  • 2
  • 67
  • 81
  • Thank you so much for the link. Now I know there is a selector :filled –  Dec 03 '15 at 06:29
  • if we use remote rules means , then this wont work. it will check only the required property but remote will work as it as in normal flow. – Varadha31590 May 10 '16 at 11:27
  • 5
    Is it possible to call a function in the required section and let it to be evaluated as true or false based on condition? for example `required: checkCondition()` – Saroj Jan 20 '17 at 07:56
  • 4
    @SarojSasmal yes - see the documentation link in the answer, the last example is what you're asking – Ryley Jan 20 '17 at 18:25
  • hmm, and how does this work with a select option dropdown??? I need a required if a specifc dropdown has a value – alex Feb 05 '18 at 11:37
8

You can use a custom validation method. For example:

jQuery.validator.addMethod("checkA", function(value, element) {
    return YourValidationCode; // return true if field is ok or should be ignored
}, "Please complete A");

then use it in your rules:

rules: {
    ....
    field_a: {
        required: false,
        checkA: true
    },
    ....
}

Take a look: http://jqueryvalidation.org/jQuery.validator.addMethod/

Gorsky
  • 99
  • 3
4

jQuery validate with condition as a function result (adding on to Ryley's comment above):

$("#Form_Id").validate({
    rules: {
        CompletedBy: "required", //straight forward validation of field
        Contact_No: "required",
        Location: { required: noTableRow }//if no table row, make Location mandatory
    }        
});

//checks whether a table row exists
function noTableRow() {
  return $("tr.tr_class").length == 0;
}
Jaggan_j
  • 488
  • 1
  • 8
  • 9
3

Edit: I did not understand the question properly at first, I apologize for that :P But, here's a solution that should work.

What you can do is check whether or not the checkbox is checked and then set the required rule for paypal_address as such:

 var checked = false;
 $( "#paypalCheckbox" ).on( "click", function() {
      checked = $('#paypalCheckbox').is(':checked');
  });

And then in the rules you can add:

 paypal_address : {
 required: checked
 }
Rohit
  • 300
  • 1
  • 11
  • Hi mate - I have the validation working ok - what I am trying to do is have additional rules based on what the user has selected. e.g if user checks the 'paypal' checkbox - then the field called 'paypal_address' needs to be completed. If they do not select this, then they can skip this field without needing to add a valid email address to the paypal_address field. – Zabs Oct 23 '13 at 13:50
  • He is using jQuery validator, you create methods, and no need to create onClick() events, since the validate() will handle everything – HomeMade Aug 14 '19 at 14:12
1

similar to the answer @Gorsky gave, but instead of registering a new validation method, you can simply make it a function.

rules: {
....
field_a: {
    required: function() {
      // return true or false depending on whether it's required or not
      return $('input[name="radioA"]:checked').val() == 1;
    }
},
....
}
Chris Geirman
  • 9,474
  • 5
  • 37
  • 70