How to reuse data in FluentValidation

For example, I have a 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 database calls with the same method. How can I call him once and reuse 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 that don't write these lambda expressions all the time to retrieve the property? How and where to save the model, and then use it later.

Simple and easy to use solutions would be nice!

+4
source share
2 answers

# 1, , . , , ( , , . MVC ). , .

(Edit: Must, )

# 2, . {PropertyValue} placeholder, . "Must" (PredicateValidator), .

, : https://github.com/JeremySkinner/FluentValidation/wiki/c.-Built-In-Validators

+4

1

2 1, , " ,

:

public class MyValidator : Validator<UserAccount>
{
    private int? _countOfExistingMails;
    private string _currentEmail;
    private object locker = new object();

    public MyValidator()
    {
        CallEmailValidations();
        // other rules...
    }
}

. Must , :

public void CallEmailValidations()
{
    RuleFor(o => o.Email).Must(x => EmailValidation(x, 0))
        .WithMessage("User with provided Email was not found in database!");

    RuleFor(o => o.Email).Must(x => EmailValidation(x, 1))
        .WithMessage("There are multiple users with provided Email in database!");
}

:

public bool EmailValidation(string email, int requiredCount)
{
    var isValid = false;

    lock(locker)
    {
        if (email != _currentEmail || _currentEmail == null)
        {
            _currentEmail = email;
            _countOfExistingMails = (int)GetDataDataFromDB(email);
        }

        if (requiredCount == 0)
        {
            isValid = _countOfExistingMails != 0; // Rule 1
        }
        else if (requiredCount == 1)
        {
            isValid = _countOfExistingMails <= 1; // Rule 2
        }
    }
    // Rule N...

    return isValid;
}

UPDATE: , .

2

:

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

"# " :

, , # 3 ,

Gotchas:

  • this -. , . .

  • , DataContext GetDataDataFromDB. , , - .

+1

All Articles