Can anyone tell me why client side validation is not working in my MVC 4 application.
@Scripts.Render("~/bundles/jquery")
@R
In Global.asax.cs, Application_Start() method add:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));
I had the same problem. It seems that the unobtrusive validation scripts were not loaded (see screenshot at the end). I fixed it by adding at the end of _Layout.cshtml
@Scripts.Render("~/bundles/jqueryval")
The end result:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@RenderSection("scripts", required: false)
Except for my pretty standard CRUD views everything is Visual studio project template defaults.
Loaded scripts after fixing the problem:
The reason that the validation data-* attributes aren't showing in the rendered html for your input could be that there is no form context. The FormContext is created automatically when you create a form using @using(Html.BeginForm(...)) { ... }
.
If you use a regular html tag for your form, you won't get client-side validation.
Ensure that you are using Attributes
(e.g. RequiredAttribute
) which comes under System.ComponentModel.DataAnnotations
namespace
you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
to
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*"));
and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)
There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:
@using (Html.BeginForm())
{
...
@Html.TextBoxFor(x => x.AgreementNumber)
}
Also I don't know what the jquery.validate.inline.js
script is but if it somehow depends on the jquery.validate.js
plugin make sure that it is referenced after it.
In all cases look at your javascript console in the browser for potential errors or missing scripts.