How to use FluentValidation in C # application

I am creating an application that has the following layers

Data structure context - Entity Framework Entity Framework Objects POCO Service - WebApi is called to load / save WebApi object -

Now I believe I should put my business logic in the service layer since I have a service for objects, for example I have a Family object and a Family Service.

To create a validation object using FluentValidation it seems like you have to inherit from AbstractValidator, since my services are already inheriting from the object, is this not possible (or is it)?

I guess my only option is to create a FamilyValidator at the service level and call that validator from the service?

Is fluentValidation my best option or am I confusing something here?

+3


source to share


1 answer


If you have an object 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;

      

+8


source







All Articles