How to use FluentValidation within c# application

asp.net-web-api business-logic c# entity-framework fluentvalidation

Question

The application I'm developing has the following layers:

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

Now that I have a service for entities, such as a family object and a family service, I think I should put my business logic there.

Since my services already derive from an object, it appears that you must inherit from AbstractValidator in order to create a validation object using FluentValidation. Is this true?

Creating a FamilyValidator at the service layer and calling it from within the service seems to be my only choice.

Is fluentValidation the better choice for me, or am I misinterpreting this?

1
3
10/21/2014 12:12:54 PM

Accepted Answer

You would create a validator for an entity called Customer like follows:

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


Related Questions





Related

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