How to use FluentValidation within c# application business-logic c# entity-framework fluentvalidation


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?

10/21/2014 12:12:54 PM

Accepted Answer

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;
10/22/2014 11:25:53 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow