Home MVC 4 client side validation not working

# MVC 4 client side validation not working

Javid
1#
Javid Published in 2013-01-25 10:55:08Z

Can anyone tell me why client side validation is not working in my MVC 4 application.

### _layout.schtml

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


In my web.config I have:

<appSettings>
</appSettings>


In 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>
<br />
@Html.TextBoxFor(x => x.UserName, new { size = "30" })
<br />
<br />
<br />
</li>
<li>
<br />
<br />
<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;">
</div>

}


In the bottom of login page:

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


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

Running the application, on login page when viewing page source, I see this rendered:

<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 in this in the bottom:

<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; }

public string UserName { get; set; }

public string Password { get; set; }

[MyDisplay("RememberMeCheckBox")]
public bool RememberMe { get; set; }
}


MyRequired is a class derived from the regular RequiredAttribute. The reason is that my error messages are localised by overriding the FormatErrorMessage(string name) method of the RequiredAttribute class. And it works fine - My labels and error messages are localized.

### MyRequired.cs

public class MyRequiredAttribute : RequiredAttribute
{

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 put a breakpoint in the POST version of my login action method, and it is being hit. The form is posted to server where server side validation happens. Client side validation doesn't happen.

What am I missing?

Thank you.

Liviu M.
2#
Liviu M. Reply to 2013-07-01 07:18:27Z
 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:
Lara85
3#
 Be sure to add this command at the end of every view where you want the validations to be active. @section Scripts { @Scripts.Render("~/bundles/jqueryval") } 
Darin Dimitrov
4#
Darin Dimitrov Reply to 2013-01-25 11:03:00Z
 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.
firecape
5#
 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 :)
saniokazzz
6#
 In Global.asax.cs, Application_Start() method add: DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter)); 
user1172763
7#
 I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:   It's a bit off-topic, but I'm continually amazed by how often this sort of thing happens in Web programming, i.e. everything seems to be in place but some obscure tweak turns out to be necessary to get things going. Flimsy, flimsy, flimsy.
TheCodingFrog
8#
 If you use jquery.validate.js and jquery.validate.unobtrusive.js for validating on client side, you should remember that you have to register any validation attribute of any DOM element on your request. Therefor you can use this code: $.validator.unobtrusive.parse('your main element on layout');  to register all validation attributes. You can call this method on (for example) : $(document).ajaxSuccess() or \$(document).ready() to register all of them and your validation can be occurred successfully instead of registering all js files on cshtml files.
Bennor McCarthy
9#
Bennor McCarthy Reply to 2013-01-25 11:05:02Z
 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.
stom
10#
 I had an issue with validation, the form posts then it validates, This Doesn't work with jquery cdn   This Works without jquery cdn   Hope helps someone.
Maarten Kieft
11#
Maarten Kieft Reply to 2016-01-06 09:24:52Z
 In my case the validation itself was working (I could validate an element and retrieve a correct boolean value), but there was no visual output. My fault was that I forgot this line @Html.ValidationMessageFor(m => ...) The TS has this in his code and got me on the right track, but I put it in here as reference for others.
Dr Blowhard
12#
Dr Blowhard Reply to 2013-01-25 11:01:33Z
 the line below shows you haven't set an DataAttribute like required on AgreementNumber   you need [Required] public String AgreementNumber{get;set;} 
Sam
13#
   This code worked for me.
Jon Koeter
14#
Jon Koeter Reply to 2016-11-01 11:06:43Z
 For me this was a lot of searching. Eventually I decided to use NuGet instead of downloading the files myself. I deleted all involved scripts and scriptbundles and got the following packages (latest versions as of now) jQuery (3.1.1) jQuery Validation (1.15.1) Microsoft jQuery Ubobtrusive Ajax (3.2.3) Microsoft jQuery Unobtrusive Validation (3.2.3) Then I added these bundles 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 reference to _Layout.cshtml: @Scripts.Render("~/bundles/jquery")  And I added this reference to whichever view I needed validation: @Scripts.Render("~/bundles/jqueryval")  Now everything worked. Don't forget these things (many people forget them): Form tags (@using (Html.BeginForm())) Validation Summary (@Html.ValidationSummary()) Validation Message on your input (Example: @Html.ValidationMessageFor(model => model.StartDate)) Configuration () The order of the files added to the bundle (as stated above)
15#
Gaurav Gandhi
16#
Gaurav Gandhi Reply to 2017-03-30 13:25:08Z
 I created this html 
where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.
Community
17#
 I'll like to add to this post, that I was experienceing the same issue but in a PartialView. And I needed to add   To the partial view, even if already present in the _Layout view. References: Data Annotations / Validation not working for partial views
  @section Scripts { }