asp.net mvc FluentValidation 的使用

原文

  1. Create a new ASP.NET MVC 3  project using the default Visual Studio Template
  2. Download the latest FluentValidation.NET
  3. Reference the FluentValidation.dll and FluentValidation.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" />
}
原文地址:https://www.cnblogs.com/philzhou/p/2490253.html