我正在尝试使Fluent Validation能够在我的客户端验证上正常工作。我正在使用ASP.NET MVC 3。
我有一个必填的标题,它的长度必须在1到100个字符之间。因此,当我输入标题时,将显示一条错误消息,该错误消息不在我的规则集中。这是我的规则集:
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.Length(1, 100)
.WithMessage("Title must be less than or equal to 100 characters");
这是显示的错误消息:
Please enter a value less than or equal to 100
我不确定自己在做什么错。这是我的global.asax:
// FluentValidation
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
new AttributedValidatorFactory());
最佳答案
对我来说很好。步骤如下:
FluentValidation.dll
和FluentValidation.Mvc.dll
程序集(请注意.zip中有两个文件夹:MVC2和MVC3,因此请确保选择正确的程序集)添加模型:
[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
public string Title { get; set; }
}
和一个相应的验证器:
public class MyViewModelValidator : AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x => x.Title)
.NotEmpty()
.WithMessage("Title is required")
.Length(1, 5)
.WithMessage("Title must be less than or equal to 5 characters");
}
}
添加到
Application_Start
中:DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
new AttributedValidatorFactory());
添加 Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
以及相应的 View :
@model SomeApp.Models.MyViewModel
@{
ViewBag.Title = "Home Page";
}
<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.TextBoxFor(x => x.Title)
@Html.ValidationMessageFor(x => x.Title)
<input type="submit" value="OK" />
}
现在尝试提交表单,将“标题”输入留空=>客户端验证开始,并显示“标题为必填”消息。现在开始输入一些文本=>错误消息消失。在输入框中输入超过5个字符后,将显示“标题必须少于或等于5个字符”的验证消息。因此,一切似乎都按预期进行。
关于asp.net-mvc - 流利的验证不起作用的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4713985/