[英]jquery validation not showing error message
这是我运行此代码时的脚本代码它没有显示任何消息它只显示必填字段的红色文本框但我想在文本框下方显示错误消息
(function ($, W, D) {
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function () {
$("#register-form").validate({
rules: {
FirstName: "required",
LastName: "required",
},
messages: {
FirstName: "Please enter your firstname",
LastName: "Please enter your lastname",
},
submitHandler: function (form) {
form.submit();
}
});
}
}
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
这是我的视图代码
<form action="" method="post" id="register-form" novalidate="novalidate">
<div class="col-md-6">
<div class="panel panel-default nobottommargin">
<div class="panel-body" style="padding: 40px;">
<div class="heading-block fancy-title nobottomborder title-bottom-border">
<h4>Registration</h4>
</div>
@using (Html.BeginForm("Registration", "Account"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
//this is model binding in mvc
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>
在您的View 中使用
@Scripts.Render("~/bundles/jqueryval")
这将引用将处理客户端验证的 jquery.validate javascript。
在您的Model类中,将[Required]属性用于您的类属性。
[Required]
public string FirstName{ get; set; }
如果 ModelState 无效/不符合您的要求,则在您的控制器内部返回模型。
if (!ModelState.IsValid)
{
return View(model);
}
只显示红色文本框而不是消息
那是因为您已经告诉它只显示自定义错误而不显示属性错误
改变
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
到
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
那么您将在摘要框中以及@Html.ValidationMessageFor
中收到属性错误 - 因此您应该删除这些错误
如果您在@Html.ValidationMessageFor
也没有收到属性错误,那么您还没有将您的验证与这两个 MVC 帮助程序结合使用 - 您希望它们做一些他们不做的事情。
所有的验证应该是两个客户端和服务器端。 通过应用服务器端属性(视图模型上的[Required]
)并使用 unobtrusive.js,您将自动获得两者,而无需将所有内容编写两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.