7

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?

Gillardo
  • 9,518
  • 18
  • 73
  • 141
  • I think you are confusing things, you don't make your service class inherit from abstract validator, you have a stand alone validator class that your service uses. – Ben Robinson Oct 21 '14 at 12:28
  • Do you mean that "Family" is your entity that you want to validate? If this is the case you don't need for your entity to inherit from abstractValidator, but you need to create a validator class that inherits from AbstarctValidator and that validator will pass Family entity as the generic parameter to the AbstractValidator. – Omar.Alani Oct 21 '14 at 12:32
  • Check this example tbat validate customer entity https://fluentvalidation.codeplex.com – Omar.Alani Oct 21 '14 at 12:43

1 Answers1

17

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;
Omar.Alani
  • 4,050
  • 2
  • 20
  • 31