- Create a new ASP.NET MVC 3 project using the default Visual Studio Template
- Download the latest FluentValidation.NET
- Reference the
FluentValidation.dll
andFluentValidation.Mvc.dll
assemblies (be careful there are two folders inside the .zip: MVC2 and MVC3 so make sure to pick the proper assembly)
新建一个Model
[Validator(typeof(MyViewModelValidator))]
public class MyViewModel
{
public string Title {get;set;}
}
以及相应的Validator
public class MyViewModelValidator:AbstractValidator<MyViewModel>
{
public MyViewModelValidator()
{
RuleFor(x=>x.Title)
.NotEmpty().WithMessage("pls enter title!")
.Length(1,5).WithMessage("less than 5 and more than 1");
}
}
在 Glabal.ass Application_Start中添加
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
ModelMetadataProviders.Current = new FluentValidationModelMetadataProvider(
new AttributedValidatorFactory());
页面代码
@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" />
}