Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Chaining validators with "Or" syntax

$
0
0
Well I think that I have found a way to do it:
public static IRuleBuilderOptions<T, TProperty> Or<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, IPropertyValidator propertyValidator)
{
    return rule.Configure(propertyRule => doStuff(propertyRule, propertyValidator));
}

private static void doStuff(PropertyRule propertyRule, IPropertyValidator propertyValidator)
{
    if (propertyRule.CurrentValidator.GetType() == typeof (AnyChildValidatorSucceedsValidator))
    {
        ((AnyChildValidatorSucceedsValidator)propertyRule.CurrentValidator).AddValidator(propertyValidator);
    }
    else
    {
        propertyRule.ReplaceValidator(propertyRule.CurrentValidator, new AnyChildValidatorSucceedsValidator(propertyRule.CurrentValidator, propertyValidator));
    }
}
The AnyChildValidatorSucceedsValidator (for lack of imagination) maintains a collection of validators and returns no failures if any of the children succeed or all the failures if all the children fail.

One thing that concerns me is that PropertyRule rule is defined in FluentValidation.Internal and the IRuleBuilderOptions.Configure passes it directly and not an interface.

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>