Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation - pre-validation / conditional validation with no code duplication

I'm trying to create Validation which is able to have two groups and block second validation if first fail (it contains many rules).

For now I did create a private 'BasicValidation' class inside and in 'main validator' do sth like this:

RuleFor(m => m).SetValidator(new BasicValidation()).DependentRules(() => {
//Complex validation
RuleFor(m => m.IdOfSthInDb)
    .MustAsync(ItemMustExists)
    .WithMessage("Item does not exist.");
});            

It does the trick but I would like to avoid creating that 'BasicValidation' for each model.

like image 313
nilphilus Avatar asked Sep 05 '18 08:09

nilphilus


1 Answers

I think hext code would solve your problem:

var basicValidator = new BasicValidation();
RuleFor(m => m).SetValidator(basicValidator));

When(m => basicValidator.Validate(m).IsValid, () => 
{
    RuleFor(m => m.IdOfSthInDb)
        .MustAsync(ItemMustExists)
        .WithMessage("Item does not exist.");
});
like image 55
Evgeny Levin Avatar answered Oct 23 '22 08:10

Evgeny Levin