Donate

$.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
$.validator.unobtrusive.adapters.addBool() Not Working In ASP.NET MVC 5 CheckBoxFor()
That's it. :-)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations