Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse data in FluentValidation

For example I have validator with two validation rules:

// Rule 1
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) != 0)
    .WithMessage("User with provided Email was not found in database!");

// Rule 2
RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
    .WithMessage("There are multiple users with provided Email in database!");

As you can see there are two calls to database with same method. How do I call it once and reuse the data for other rules?

Another issue when displaying error messages:

RuleFor(o => o.Email).Must((email) => this.GetDataDataFromDB(email) >= 1)
    .WithMessage("There are multiple users with following Email '{0}' in database!",
    (model, email) => { return email; });

Is there a better way to display error messages not all the time writing those lambda expressions to retrieve property? Like saving model somewhere and then use it later.

Simple and easy to implement solutions would be nice!

like image 306
Mr. Blond Avatar asked May 27 '16 13:05

Mr. Blond


Video Answer


1 Answers

For #1, There isn't a way to do this I'm afraid. Validators are designed to be stateless so they can be reused across threads (in fact, it's highly recommended you create validator instances as singletons as they're very expensive to instantiate. The MVC integration does this by default). Don't mess with static fields as you'll run into threading issues.

(Edit: in this particular simple case you can just combine the rules into a single call to Must, but in general you can't share state between rules)

For #2, This depends on the property validator you're using. Most property validators actually allow you to use the {PropertyValue} placeholder, and the value will automatically be inserted. However, in this case you're using the "Must" validator (PredicateValidator) which doesn't support placeholders.

I have a list of which validators support custom placeholders here: https://github.com/JeremySkinner/FluentValidation/wiki/c.-Built-In-Validators

like image 90
Jeremy Skinner Avatar answered Sep 30 '22 20:09

Jeremy Skinner