创建业务模型验证器的最佳方法是什么?

时间:2014-07-21 23:28:49

标签: c# model validation

有人能指出我如何设计最佳模型验证器吗?最好的,我的意思是一种设计,它将最大限度地提高可重用性并易于使用。 如果我有一个客户,并且有firstName,lastName和DOB以及一个地址,我希望firstName是必需的,至少需要2个字符长。并且还需要地址。但是,如果您说拥有地址的发布者,则在这种情况下地址可以是可选的。 我想要像:

if(obj.IsValid())
{
  //do stuff
}
else{
 var validationErrors = obj.GetValidationErrors();// and this should give me each property along with the validation that failed along with the error messages.
}

如何设计这样的东西? 谢谢,

1 个答案:

答案 0 :(得分:1)

您可以尝试Fluent Validator,您可以拥有多个验证规则。

Install-Package FluentValidation

实施例

using FluentValidation;

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.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 = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;