Search code examples
asp.net-mvcjquery-validateunobtrusive-validation

MVC Form Data Validation and jquery validation


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!");

Solution

  • 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.