Nop-關於FluentValidation與驗證

Nop-關於FluentValidation與驗證<二>

分類: Nop Commerce 32人閱讀 評論(0) 收藏 舉報

在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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章