Donate

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 () {
    
    $("#frmInput").validate({
        submitHandler: function (form) {
            //submit once validation rules are met
            form.submit();           
        },
        .....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.

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

2. Change rendering of scripts code in _Layout.cshtml
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/jquery")   
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/RegistrationFormValidation") @* validate form *@
@Scripts.Render("~/bundles/jqueryunobtrusive") 
@Scripts.Render("~/bundles/modernizr") 

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

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