我使用流畅的验证与客户端不显眼的验证。
<fieldset class="edit-root-form">
<p>
@Html.LabelFor(model => model.Login, UserRes.Login)
@Html.TextBoxFor(model => model.Login)
@Html.ValidationMessageFor(model => model.Login)
</p>
</fieldset>
流利的验证规则:
this.RuleFor(x => x.Login).NotNull().EmailAddress()
我收到如下错误消息:' {PropertyName} '不能为空。
Genered html:
<input data-val="true" data-val-regex="&#39;{PropertyName}&#39; is not a valid
email address." data-val-required="&#39;{PropertyName}&#39; must not be
empty." id="Login" name="Login" type="text" value="" class="input-validation-error">
为什么MVC不能替换 PropertyName 真实字段名称?
答案 0 :(得分:3)
对我来说很好。我使用的是最新的FluentValidation版本(2.0.0.0)和ASP.NET MVC 3 RTM。
模型和验证器:
[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
public string Login { get; set; }
}
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x => x.Login).NotNull().EmailAddress();
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
查看:
@model AppName.Models.MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.Login, "Login")
@Html.TextBoxFor(model => model.Login)
@Html.ValidationMessageFor(model => model.Login)
<input type="submit" value="OK" />
}
Application_Start
中的 Global.asax
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
}
两种情况:
'Login' must not be empty.
验证错误消息。'Login' is not a valid email address.
验证错误消息。最后,这是为文本框生成的HTML:
<input data-val="true" data-val-regex="&#39;Login&#39; is not a valid email address." data-val-regex-pattern="^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$" data-val-required="&#39;Login&#39; must not be empty." id="Login" name="Login" type="text" value="" />