JacobIRR
JacobIRR

Reputation: 8966

jQuery validate() for radio buttons with same name, different values

If I have this HTML:

<div class="form-group radioInput">
  <label class="radio-inline">
    <input checked="checked" name="AcknowledgeLSA" type="radio" value="False"> No
  </label>
  <label class="radio-inline">
    <inputname="AcknowledgeLSA" type="radio" value="True"> Yes
  </label>
</div>

And this psuedo-JS (which obviously doesn't work):

myForm.validate({
    rules: {
        AcknowledgeLSA:checked : {required: value="True"}
    }
});        

... how can I have the validation based on the value of the Radio Button being "True"?

I'm needing to change the JS not the HTML. The form is valid if the radio button with the True value is selected. The form is not valid is the other False radio button is checked.

Upvotes: 0

Views: 1408

Answers (2)

Rahul D&#39;Mello
Rahul D&#39;Mello

Reputation: 100

i think you need to use depends here:

myForm.validate({
    rules: {
        AcknowledgeLSA: {
            required: true,
            depends: function() { 
                         var rbtn = $("input[name='AcknowledgeLSA']:checked");
                         return typeof rbtn !== 'undefined' && rbtn.val() == "True";
                }
        }
    }
});

EDIT: You can create a custom rule like this:

jQuery.validator.addMethod("hasValue", function(value, element, param) {
    return value == param;
}, 'Invalid!');

myForm.validate({
    rules: {
        AcknowledgeLSA: {
            hasValue: 'True'
       }
};

Upvotes: 1

iCreateAwesome
iCreateAwesome

Reputation: 4464

myForm.validate({
rules: 
    AcknowledgeLSA : {
        required: true,
        depends: function() { return $('[name="AcknowledgeLSA"]').is(':checked').val() === "True";}
    }
}
});

https://jqueryvalidation.org/validate/#rules

Upvotes: 0

Related Questions