.NET用のシンプルなバリデータ「Fluent Validation」

.NET用のシンプルなバリデータ「Fluent Validation for .NET

トップページのコード例は以下のような感じ。

//-------------------------
//Customer用のバリデータを宣言
//-------------------------
public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    //プロパティ毎の妥当性チェックを設定
    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) {
    // バリデイト後のカスタマイズコード
  }
}

//-------------------------
//バリデータを試すコード
//-------------------------
Customer customer = new Customer();
//バリデータを使用
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
//結果を取得
bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;

ラムダとメソッドチェーンで、妥当性チェックコードを簡単に書けるのが売りです。