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.
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
2. Change rendering of scripts code in _Layout.cshtml
Note: There may be other solutions as to why form.validate() does not work. This is just a workaround.
$(function () { $("#frmInput").validate({ submitHandler: function (form) { //submit once validation rules are met form.submit(); }, .....other codes here }); });
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
Post a Comment