-1

I am using MVC Data Validation for TextBoxFor and DropDownListFor and its working nice. But I also wanted to add jquery validation for checkbox list is there a way to add that as well? In my document.ready function I call ready validate(); which add the validator.addMethod but it is not firing.

 <button type="submit" class="btn btn-primary px-4 float-right">Save</button>


 $(document).ready(function () {
validate();
}

var validate = function () {
            $.validator.addMethod("sources", function (value, elem, param) {
                if ($("[name='chkProduct']:checkbox:checked").length > 0) {
                    return true;
                } else {
                    return false;
                }
            }, "You must select at least one!");
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • A checkbox only has on or off, how do you select more than one? – mxmissile Feb 05 '21 at 17:43
  • Sorry is a checkbox list –  Feb 05 '21 at 17:51
  • 3
    Does this answer your question? [Check if checkbox is checked with jQuery](https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery) – Archerspk Feb 05 '21 at 18:15
  • By default, the plugin makes at least one checkbox required when the `required` rule is properly applied to a `checkbox` group. – Sparky Feb 09 '21 at 18:19

1 Answers1

0

Try using your checkbox as follows:

<fieldset id="checkArray">
<input type="checkbox" name="chk[]" value="Apples" />

<input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

And then validate via Jquery like this:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

Then you can use atLeastOneIsChecked to verify if there are any checked boxes or not ( true or false ) and do wathever you want.

Archerspk
  • 137
  • 11
  • Trying to figure out why this is needed. The plugin already does the exact same thing when the `required` rule is applied to a `checkbox` group. – Sparky Feb 09 '21 at 18:17