Saturday, February 13, 2016

ASP.NET MVC 5 jQuery validation form.validate() method in external JavaScript file not firing

I have an external JavaScript file that validates a form using form.validate() of jQuery validation plugin.
$(function () {
        submitHandler: function (form) {
            //submit once validation rules are met
        .....other codes here

When integrating it in an MVC 5 application, the validate event does not trigger. I have checked if there are errors using the Chrome developer tools and Firefox but to no avail there is none. The solution I discovered was to change the BundleConfig.cs file and the order of scripts rendering in _Layout.cshtml. After that, form validation now works.

1. Change BundleConfig.cs codes
//change code in BundleConfig.cs From:
bundles.Add(new ScriptBundle("~/bundles/jqueryval")
//To: (individual bundling of validate and unobtrusive js files)
bundles.Add(new ScriptBundle("~/bundles/jqueryval")
bundles.Add(new ScriptBundle("~/bundles/jqueryunobtrusive")

2. Change rendering of scripts code in _Layout.cshtml
@Scripts.Render("~/bundles/RegistrationFormValidation") @* validate form *@

Note: There may be other solutions as to why form.validate() does not work. This is just a workaround.


Post a Comment