Wednesday, February 15, 2017

$.validator.unobtrusive.adapters.addBool() not working in ASP.NET MVC 5 CheckBoxFor().

I was testing the addBool() method of jQuery validation to a CheckBoxFor() which will prevent the form from submitting if the checkbox is unchecked. To my surprise, the JavaScript code below doesn't work.
    <script type="text/javascript" language="javascript">
        (function ($) {

            $.validator.addMethod('checkboxrequired', function (value, elem) {
                var $elem = $(elem);
                if ($elem.prop('type') == 'checkbox') {
                    if (!$elem.prop('checked')) {
                        return false;
                return true;
            $.validator.unobtrusive.adapters.addBool('checkboxrequired', 'required');
After series of investigation, I discovered that the jQuery and jQueryValidation scripts have been rendered twice on the page since it has reference to a Layout page that also rendered the jQuery and jQueryValidation scripts.

To fix the issue, I removed the statements @Scripts.Render("~/bundles/jquery") and @Scripts.Render("~/bundles/jqueryval") in my Validation.cshtml page. In my Layout.cshtml page, I transferred the rendering of jQuery and jQueryValidation statements just below the @Scripts.Render("~/bundles/modernizr") statement.

That's it. :-)


Post a Comment