How to validate a list of checkbox through custom jQuery in asp.net mvc

馋奶兔 提交于 2019-12-04 19:37:00

You cannot achieve that using MVC's client side validation (by implementing IClientValidatable and using jquery.validation.unobtrusive.js). The reason is that client side validation rules are applied to form controls, and you do not (and cannot) create a form control for your skills property which is a collection, not a simple value type.

You need to write your own scripts to validate the number of checked checkboxes (and if not valid, make use of the placeholder generated by @Html.ValidationMessageFor(model => model.skills)

To mimic jquery's 'lazy' validation, initially handle the .submit() event, and there after, handle the .click() event of the checkboxes.

Modify your 2nd <td> element to add an id attribute for selecting the checkboxes (see also notes below)

<td id="skills">
    .... // your checkboxes

and add the following scripts

var validateSkillsOnCheck = false; // for lazy validation
var requiredSkills = 3;
var skills = $('#skills input[type="checkbox"]');
var errorMessage = 'Select at least 3 skills';
var errorElement = $('span[data-valmsg-for="skills"]');

// function to validate the required number of skills
function validateSkills() {
    var selectedSkills = skills.filter(':checked').length;
    var isValid = selectedSkills > requiredSkills;
    if (!isValid) {
        errorElement.addClass('field-validation-error').removeClass('field-validation-valid').text(errorMessage);
    } else {
        errorElement.addClass('field-validation-valid').removeClass('field-validation-error').text('');
    }
    return (isValid);
}

$('form').submit(function () {
    validateSkillsOnCheck = true;
    if (!validateSkills()) {
        return false; // prevent submit
    }
});
$('#skills').on('click', 'input', function () {
    if (validateSkillsOnCheck) {
        validateSkills();
    }
})

A few side notes.

  1. Tables are for tabular data, not layout and using a <table> element is not appropriate in your case.
  2. Your @Html.LabelFor(model => model.skills) is not appropriate (you do not have a form control for skills so clicking on it does not set focus to anything). That should just be a <span>@Html.DisplayNameFor(m =>m.skills)</span> or similar element.
  3. You should however be creating labels for each checkbox. Your model has 3 properties including Text and Value and its not clear what the difference is between them, and in any case, you never include them in the view. I assume your will want to submit at least the Value property so you know which skills have been selected

    <label>
        @Html.CheckBoxFor(m =>m.skills[i].IsChecked)
        <span>@Model.skills[i].Text</span>
    </label>
    @Html.HiddenFor(m =>m.skills[i].Value)
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!