How to use FluentValidation within c# application

Gillardo picture Gillardo · Oct 21, 2014 · Viewed 10.5k times · Source

I am building an application that has the following layers

Data - Entity Framework Context Entities - Entity Framework POCO objects Service - Called by WebApi to load/save entity WebApi -

Now i believe that i should put my business logic into the Service layer, as i have a service for entities, for example, i have Family object and a Family Service.

To create a validation object using FluentValidation, it seems that you must inherit from AbstractValidator, since my services already inherit from an object this isnt possible (or is it)?

I guess my only option is to create a FamilyValidator in the service layer and call this validator from within the service?

Is fluentValidation my best option, or am i confusing things here?

Answer

Omar.Alani picture Omar.Alani · Oct 22, 2014

If you have an entity called Customer, this is how you write a validator for it:

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;