对我来说很好。以下是步骤:
- 使用默认的 Visual Studio 模板创建一个新的 ASP.NET MVC 3 RTM 项目
- 下载最新的FluentValidation.NET
- 引用
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());
添加控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
和相应的视图:
@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" />
}
现在尝试提交表单,将 Title 输入留空 => 客户端验证启动,并显示Title is required 消息。现在开始输入一些文本 => 错误消息消失。在输入框中键入超过 5 个字符后,将显示标题必须小于或等于 5 个字符验证消息。所以一切似乎都按预期工作。