Wednesday, February 15, 2017

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

Hello,
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.
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    <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');
            
        }(jQuery));
    </script>
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.
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")

Screenshot
That's it. :-)

0 comments:

Post a Comment