0

I have used fluent validation for hard code validations like this:

RuleFor(customer => customer.CreditLimit).GreaterThan(customer => customer.MinimumCreditLimit);

I guess it would not be a problem to replace MinimumCreditLimit by some (meta) database driven value in the code. Did someone ever attempt this and what would be the best practises in this context (apart from the fact that MinimumCreditLimit could stem from some strategy design pattern). Could one potentially use expression trees against fluent validation to make it even more meta program-ish?

cs0815
  • 16,751
  • 45
  • 136
  • 299

1 Answers1

1

Well, the easiest way would be to add a ctor to your Validation class.

public class EntityValidator : AbstractValidator<Entity> {
  public EntityValidator(int minimumCreditLimit) {
         Rulefor(customer => customer.CreditLimit).GreaterThan(minimumCreditLimit); 
  }
}

now you could use it like that (if you don't use the "attributes" way).

var minimumCreditLimit = <GetTheLimitFromDbWithAnyMethod>();
var validator = new EntityValidator(minimumCreditLimit);
<yourEntityInstance>.ValidateAndThrow(validator);

Another (similar) way would be to pass some way to get data from db to your validator (in ctor for example), and create a custom validator / extension method to use this.

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122