Custom clientside validation for required at least one in array

痞子三分冷 提交于 2019-12-06 06:09:46

So this was fixed with the following changes to the html:

<input type="checkbox" class="checkbox required-group" name="ProductIds" value="EXAMPLEID1234" id="checkbox-1" checked="checked" data-val-required="Please select at least one sample" />
<input type="checkbox" class="checkbox required-group" name="ProductIds" value="EXAMPLEID1235" id="checkbox-2" checked="checked" />

data-val-required only needs to be on the first checkbox in the array. Then using the following jQuery:

(function ($) {
    $.validator.addMethod('requiredarray', function (value, element, params) {
        return $('input[name=' + $(element).attr('name') + ']:checked').length > 0;
    }, 'Please select at least one');

    $.validator.addClassRules('required-group', { 'requiredarray': true });

    var errorMessage = $('.required-group').eq(0).data('val-requiredarray');
    if (errorMessage && errorMessage !== "") {
        $.validator.messages.requiredarray = errorMessage;
    }
})(jQuery);

I have changed the addBool to addClassRules and then used $.validator.messages to set the error message.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!