Client side check MVC 4 not working

Can someone tell me why client side validation does not work in my MVC 4 application.

_layout.schtml

@Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) 

In my web.config, I have:

 <appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> 

On my login.cshtml page, I have:

 @using (Html.BeginForm()) { <div class="formscontent"> <ol> <li> @Html.LabelFor(x => x.AgreementNumber) <br /> @Html.TextBoxFor(x => x.AgreementNumber, new { size = "30" }) <br /> @Html.ValidationMessageFor(m => m.AgreementNumber) <br /> <br /> </li> <li> @Html.LabelFor(x => x.UserName) <br /> @Html.TextBoxFor(x => x.UserName, new { size = "30" }) <br /> @Html.ValidationMessageFor(m => m.UserName) <br /> <br /> </li> <li> @Html.LabelFor(x => x.Password) <br /> @Html.PasswordFor(x => x.Password, new { size = "30" }) <br /> @Html.ValidationMessageFor(m => m.Password) <br /> <br /> </li> </ol> </div> <ol> <li> @Html.CheckBoxFor(m => m.RememberMe) @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" }) </li> </ol> <br /> <input class="mainbutton" type="submit" value="@Model.Localisation.TranslateHtmlString("LogonBtn")" /><br /> <div style="text-align: left; padding: 0 5px 5px 10px;"> Forgot login-info? clik <a class="link" href="@Url.Action("Index", "Credentials")">here.</a> </div> } 

At the bottom of the login page:

 @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 

JavaScript is enabled in my browser. In the MVC 4 template from the client check, Visual Studio works fine.

Launching the application, on the login page when viewing the source of the page, I see that this is shown:

 <label for="AgreementNumber">number</label> <br /> <input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" /> <br /> <span class="field-validation-valid" data-valmsg-for="AgreementNumber" data-valmsg- replace="true"></span> 

and below:

 <script src="/BMWebsite/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="/BMWebsite/Scripts/jquery.validate.inline.js"></script> <script src="/BMWebsite/Scripts/jquery.validate.js"></script> <script src="/BMWebsite/Scripts/jquery.validate.unobtrusive.js"></script> 

My model properties are annotated:

 public class LogonModel : ModelBase { [MyRequired("AgreementNumberRequiredProperty")] [MyDisplay("AgreementNumberLabel")] public string AgreementNumber { get; set; } [MyRequired("UserNameRequiredProperty")] [MyDisplay("UserNameLabel")] public string UserName { get; set; } [MyRequired("PasswordRequiredProperty")] [DataType(DataType.Password)] [MyDisplay("PasswordLabel")] public string Password { get; set; } [MyDisplay("RememberMeCheckBox")] public bool RememberMe { get; set; } } 

MyRequired is a class derived from a regular RequiredAttribute. The reason is because my error messages are localized by overriding the FormatErrorMessage(string name) method of the RequiredAttribute class. And it works great. My tags and error messages are localized.

Myrequired.cs

 public class MyRequiredAttribute : RequiredAttribute { private readonly string _errorMessagekey; public MyRequiredAttribute(string errorMessage) { _errorMessagekey = errorMessage; } public override string FormatErrorMessage(string name) { var translation = HttpContext.Current.Session["translation"] as LocalisationHelper; return translation != null ? translation.Translate(_errorMessagekey) : ErrorMessage; } } 

I set a breakpoint in the POST version of my login action method, and it hits. The form is sent to the server, where the check is done on the server side. Client side validation does not occur.

What am I missing?

Thank.

+52
jquery jquery-validate asp.net-mvc-4 unobtrusive-validation
Jan 25 '13 at 10:55
source share
20 answers

I had the same problem. It seems that unobtrusive verification scripts have not been downloaded (see the screenshot at the end). I fixed it by adding _Layout.cshtml at the end

  @Scripts.Render("~/bundles/jqueryval") 

Final result:

  @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @RenderSection("scripts", required: false) 

With the exception of my standard CRUD standard views, all Visual Studio project templates are by default.

Loaded scripts after fixing the problem: enter image description here

+46
Jul 01 '13 at 7:18
source share

Be sure to add this command at the end of each view where you want the checks to be active.

 @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 
+15
Jan 28 '16 at 9:39
source share

In the Global.asax.cs application, Application_Start (), add:

 DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter)); 
+10
Nov 24 '13 at 18:28
source share

You may have already solved this, but I was lucky to change the order of the jqueryval element in BundleConfig using App_Start. Client-side validation will not work even on the latest available MVC 4 Internet solution. Therefore, I changed the default value:

  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 works. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)

+9
Jul 13 '13 at 7:24
source share

I finally solved this problem by including the necessary scripts directly in my .cshtml file in the following order:

 <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script> 

This is a little off topic, but I am constantly amazed at how often this happens in web programming, i.e. everything seems to be in place, but some obscure settings are necessary for everything to work out. Fictitious, flimsy, flimsy.

+8
Aug 27 '15 at 17:06
source share

There are no data validation attributes on your input. Make sure you generate it using a server side helper like Html.TextBoxFor, and that it is inside the form:

 @using (Html.BeginForm()) { ... @Html.TextBoxFor(x => x.AgreementNumber) } 

Also, I do not know what the jquery.validate.inline.js script is, but if it somehow depends on the jquery.validate.js plugin, make sure it is listed after it.

In all cases, look at your javascript console in the browser for possible errors or missing scripts.

+7
Jan 25 '13 at
source share

If you use jquery.validate.js and jquery.validate.unobtrusive.js for client side validation, you should remember that you need to register any validation attribute of any DOM element for your request. For this you can use this code:

 $.validator.unobtrusive.parse('your main element on layout'); 

to register all validation attributes. You can call this method (for example): $(document).ajaxSuccess() or $(document).ready() to register them all, and your check can be successfully completed, rather than registering all js files in cshtml files.

+7
Sep 20 '15 at 7:26
source share

The reason that validation data- * attributes are not displayed in the displayed html for your input may be because there is no form context. A FormContext is created automatically when a form is created using @using(Html.BeginForm(...)) { ... } .

If you use the regular html tag for your form, you will not receive client side validation.

+3
Jan 25 '13 at 11:05
source share

I have a problem with validation, form messages are then checked,

This does not work with jquery cdn

  <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

This works without jquery cdn

 <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

Hope helps someone.

+3
May 24 '16 at 10:09
source share

For me it was a lot of searching. In the end, I decided to use NuGet instead of downloading files. I deleted all the involved scripts and scripts and received the following packages (latest versions at the moment)

  • jQuery (3.1.1)
  • JQuery validation (1.15.1)
  • Microsoft jQuery Ubobtrusive Ajax (3.2.3)
  • Microsoft jQuery Unobtrusive Check (3.2.3)

Then I added these packages to the BundleConfig file:

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate.js", "~/Scripts/jquery.validate.unobtrusive.js", "~/Scripts/jquery.unobtrusive-ajax.js")); 

I added this link in _Layout.cshtml:

 @Scripts.Render("~/bundles/jquery") 

And I added this link to any view I needed to verify:

 @Scripts.Render("~/bundles/jqueryval") 

Now everything worked.

Do not forget about it (many forget about them):

  • Form Tags (@using (Html.BeginForm ()))
  • Validation Summary (@ Html.ValidationSummary ())
  • Validation message at your input (example: @ Html.ValidationMessageFor (model => model.StartDate))
  • Configuration()
  • The order of the files added to the kit (as described above)
+3
Nov 01 '16 at 11:06
source share
 <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script> 

This code worked for me.

+2
06 Sep '15 at 11:17
source share

In my case, the check itself worked (I could check the element and get the correct logical value), but there was no visual output.

My mistake was that I forgot this line @ Html.ValidationMessageFor (m => ...)

TS has this in its code and typed me on the right track, but I put it here as a link for others.

+2
Jan 6 '16 at 9:24
source share

the line below shows that you did not set the DataAttribute attribute as required in the agreement window

 <input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" /> 

you need

 [Required] public String AgreementNumber{get;set;} 
+1
Jan 25 '13 at 11:01
source share

Using:

@ Html.EditorFor

Instead:

@ Html.TextBoxFor

0
Nov 08 '16 at 16:27
source share

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where novalidate="novalidate" prevented client-side jQuery from executing when I removed novalidate="novalidate" , Client-side jQuery was turned on and looked workable.

0
Mar 30 '17 at 12:17
source share

I want to add to this post that I was experiencing the same problem, but in PartialView.

And I needed to add

 <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

In partial view, even if it is already present in the _Layout view.

Literature:

  • Data Annotations / Validation Does Not Work for Partial Views
0
Apr 20 '17 at 15:03
source share

My problem was in web.config: UnobtrusiveJavaScriptEnabled was disabled

<appSettings>

<add key="ClientValidationEnabled" value="true"/>

<add key="UnobtrusiveJavaScriptEnabled" value="false"/>

</appSettings>

I changed to and now works:

 '<add key="UnobtrusiveJavaScriptEnabled" value="true" />' 
0
Feb 01 '18 at 12:31
source share

In my case, I added, and id is equal to the name automatically generated for VS in HTML, and in the code I added a line for this case.

 $(function () { $.validator.addMethod('latinos', function (value, element) { return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value); }); $("#btn").on("click", function () { //alert("aa"); $("#formulario").validate({ rules: { email: { required: true, email: true, minlength: 8, maxlength: 80 }, digitos: { required: true, digits: true, minlength: 2, maxlength: 100 }, nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 }, NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 } }, messages: { email: { required: 'El campo es requerido', email: 'El formato de email es incorrecto', minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres' }, digitos: { required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos', minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres' }, nombres: { required: 'El campo es requerido', latinos: 'Sólo se aceptan letras', minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres' }, NombresUsuario: { required: 'El campo es requerido', latinos: 'Sólo se aceptan letras', minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres' } } }); }); <tr>@*<div class="form-group"> htmlAttributes: new { @class = "control-label col-md-2" } , @class = "form-control" }*@ <td>@Html.LabelFor(model => model.NombresUsuario )</td> @*<div class="col-md-10">*@ <td> @Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } }) @Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" }) </td> 
0
Mar 15 '18 at 22:29
source share

Make sure you use Attributes (e.g. RequiredAttribute ) that are in the System.ComponentModel.DataAnnotations namespace

0
Jun 11 '19 at 10:51
source share
  @section Scripts { <script src="../Scripts/jquery.validate-vsdoc.js"></script> <script src="../Scripts/jquery.validate.js"></script> <script src="../Scripts/jquery.validate.min.js"></script> <script src="../Scripts/jquery.validate.unobtrusive.js"></script> <script src="../Scripts/jquery.validate.unobtrusive.min.js"></script> } 
-2
Feb 26 '15 at 9:11
source share



All Articles