您的位置:首页 > 产品设计 > UI/UE

Nop-关于FluentValidation与验证<二>

2012-02-22 14:36 281 查看
在Nop中大量使用的验证方式,包括输入验证,后台数据判断,采用FluentValication库。

A small validation library for .NET that uses a fluent interfaceand lambda expressions for building validation rules for your business objects.

一个轻量型的.NTE验证库,通过Flucent接口以及Lambda表达式来为业务逻辑对象建立验证规则,例如为PresentatilonModel以及BusinessModel。

从典型使用方式来看,首先引用FluentValidation/FluentValidation.MVC,然后就可以在代码中使用了:

using FluentValidation;
//Validator类
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
//设置各种规则,通过Lambda表达式, customer isvariable for type of Customer
RuleFor(customer =>customer.Surname).NotEmpty();
RuleFor(customer =>customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Company).NotNull();
RuleFor(customer =>customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer =>customer.Address).Length(20, 250);
RuleFor(customer =>customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}

private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
//被验证对象
Customer customer = new Customer();
CustomerValidator validator = newCustomerValidator();
//验证操作,结果存储在Results结构体中
ValidationResult results = validator.Validate(customer);
//成功/失败;以及错误消息列表
bool validationSucceeded =results.IsValid;
IList<ValidationFailure> failures = results.Errors;

本地化

默认的FluentValidation提供的信息提示包含以下语言:


English


Dutch


French


German


Portuguese


Spanish
那中文的话,就需要我们增加一些代码来处理:两种方式,使用WithLocalizedMessage方法去指定单个的验证规则的本地化错误消息;或设置全局ResourceProviderType来用自己定义的一套本地字符串替换FluentValidation的所有默认错误信息提示。

举个例子,通过指定ResourceType以及其属性名称SurnameRequiredError,实际代表一个资源文件的一个字符串。

RuleFor(x => x.Surname).NotNull().WithLocalizedMessage(() => MyLocalizedMessage.SurnameRequiredError);

需要主要的是这个Property需要是public并且Static的。

1. 打开项目,添加引用,然后增加目录Validator,添加Class类文件ProductValidator.cs

2. 增加资源文件(特别注意点: CustomerTool: PublicResXFileCodeGenerator)(Custom Tool Namespace: HWResources)

可以看到产生的属性:

public static string NotEmptyString {
get {
return ResourceManager.GetString("NotEmpty", resourceCulture);
}

3. 完成验证代码:

public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{

RuleFor(p => p.ProductID)
.NotEmpty()
.WithLocalizedMessage(() => HWResources.ServerSide.NotEmpty);  }   }


使用自定义的ResourceProvider Type:

这种方式适合批量替换默认消息,可以通过设置Validatoroptions类的ResourceProviderType属性

ValidatorOptions.ResourceProviderType = typeof(MyResources);

public class MyResources {
public static stringnotempty_error {
get {
return"{PropertyName} 是必须输入的!";
}
}
}

通过以上的方式,非空判断的默认的消息就会显示为xxx是必须输入的!

通过自定义的ResourceProvider类型,需要了解Fluent暴露出来的资源字符串名字:


email_error


equal_error


exact_length_error


exclusivebetween_error


greaterthan_error


greaterthanorequal_error


inclusivebetween_error


length_error


lessthan_error


lessthanorequal_error


notempty_error


notequal_error


notnull_error


predicate_error


regex_error

通过以上的学习,您可能会想起在Nop中有目录名为Validators其中有各个对象命名的子目录,其中又包含了XXXValidator.cs

namespaceNop.Admin.Validators.Directory
{
public class CountryValidator: AbstractValidator<CountryModel>
{
publicCountryValidator(ILocalizationServicelocalizationService)
{
RuleFor(x => x.Name)
.NotNull()
.WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.Name.Required"));

其多语言就是通过withmessage()来实现的。当然关于使用validation在NOP中,还涉及如何在MVC中使用FluentValidation.这个仅仅是开篇

更多详细资料,请参考http://fluentvalidation.codeplex.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: