简体   繁体   中英

What is the best way to create business model validator?

Can some one point me how to design best model validator? By best, i meant a design that will maximize reusability and easy to use as well. If I have a customer and that has firstName, lastName and DOB, and an address, I want firstName to be required with say at least 2 char long. And address is required as well. But if you have say a publisher with an address, address can be optional in this case. I would like something like:

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.
}

How to design something like this? Thanks,

You can try Fluent Validator , you can have multiple validation rules.

Install-Package FluentValidation

Example

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM