jQuery MVC 4 客户端验证不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14520336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC 4 client side validation not working
提问by Javid
Can anyone tell me why client side validation is not working in my MVC 4 application.
谁能告诉我为什么客户端验证在我的 MVC 4 应用程序中不起作用。
_layout.schtml
_layout.schtml
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
In my web.config I have:
在我的 web.config 我有:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
In my login.cshtml page I have:
在我的 login.cshtml 页面中,我有:
@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>
}
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.
我的浏览器启用了 JavaScript。在来自 Visual Studio 客户端验证的 MVC 4 模板项目中,工作正常。
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; }
[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 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
是从常规的RequiredAttribute 派生的类。原因是我的错误消息是通过覆盖类的FormatErrorMessage(string name)
方法来本地化的RequiredAttribute
。它工作正常 - 我的标签和错误消息已本地化。
MyRequired.cs
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 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.
我在我的登录操作方法的 POST 版本中放置了一个断点,它正在被命中。表单被发布到服务器端验证发生的服务器。客户端验证不会发生。
What am I missing?
我错过了什么?
Thank you.
谢谢你。
回答by Liviu M.
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
我有同样的问题。似乎没有加载不显眼的验证脚本(见最后的截图)。我通过在 _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.
除了我非常标准的 CRUD 视图之外,一切都是 Visual Studio 项目模板默认值。
Loaded scripts after fixing the problem:
修复问题后加载脚本:
回答by Lara85
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")
}
回答by saniokazzz
In Global.asax.cs, Application_Start() method add:
在 Global.asax.cs 中,Application_Start() 方法添加:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));
回答by user1172763
I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:
我最终通过将必要的脚本直接包含在我的 .cshtml 文件中来解决这个问题,顺序如下:
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
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.
这有点离题,但我一直对这种事情在 Web 编程中发生的频率感到惊讶,即一切似乎都已就位,但事实证明需要进行一些模糊的调整才能使事情顺利进行。脆弱的,脆弱的,脆弱的。
回答by firecape
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:
您可能已经解决了这个问题,但是我通过使用 App_Start 更改 BundleConfig 中 jqueryval 项的顺序而获得了一些运气。即使在全新的开箱即用 MVC 4 Internet 解决方案上,客户端验证也不起作用。所以我更改了默认值:
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 :)
现在我的客户端验证工作正常。你只是想确保不显眼的文件在最后(所以它不是侵入性的,哈哈:)
回答by Darin Dimitrov
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:
您的输入没有数据验证属性。确保您已使用服务器端助手(例如 Html.TextBoxFor)生成它,并且它位于表单内:
@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.
此外,我不知道jquery.validate.inline.js
脚本是什么,但如果它以某种方式依赖于jquery.validate.js
插件,请确保在它之后引用它。
In all cases look at your javascript console in the browser for potential errors or missing scripts.
在所有情况下,请查看浏览器中的 javascript 控制台是否存在潜在错误或缺少脚本。
回答by Saeed Rajaei
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:
如果您在客户端使用jquery.validate.js
和 jquery.validate.unobtrusive.js
进行验证,您应该记住您必须在您的请求中注册任何 DOM 元素的任何验证属性。因此,您可以使用此代码:
$.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.
注册所有验证属性。您可以在(例如)上调用此方法:
$(document).ajaxSuccess() or $(document).ready()
注册所有这些并且您的验证可以成功进行,而不是在 cshtml 文件上注册所有 js 文件。
回答by shaijut
I had an issue with validation, the form posts then it validates,
我有一个验证问题,表单发布然后它验证,
This Doesn't work with jquery cdn
这不适用于 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
这在没有 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.
希望能帮助某人。
回答by Jon Koeter
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)
对我来说,这是很多搜索。最终我决定使用 NuGet 而不是自己下载文件。我删除了所有涉及的脚本和脚本包,并获得了以下软件包(截至目前的最新版本)
- jQuery (3.1.1)
- jQuery Validation (1.15.1)
- Microsoft jQuery Ubobtrusive Ajax (3.2.3)
- Microsoft jQuery Unobtrusive Validation (3.2.3)
- jQuery (3.1.1)
- jQuery 验证 (1.15.1)
- 微软 jQuery Ubobtrusive Ajax (3.2.3)
- Microsoft jQuery 非侵入式验证 (3.2.3)
Then I added these bundles to the BundleConfig file:
然后我将这些包添加到 BundleConfig 文件中:
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:
我将此引用添加到 _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)
- 表单标签(@using (Html.BeginForm()))
- 验证摘要 (@Html.ValidationSummary())
- 您输入的验证消息(例如:@Html.ValidationMessageFor(model => model.StartDate))
- 配置 ()
- 添加到包中的文件的顺序(如上所述)
回答by Bennor McCarthy
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(...)) { ... }
.
验证 data-* 属性未显示在为您的输入呈现的 html 中的原因可能是没有表单上下文。当您使用@using(Html.BeginForm(...)) { ... }
.
If you use a regular html tag for your form, you won't get client-side validation.
如果您为表单使用常规 html 标记,您将不会获得客户端验证。