Skip to content

Instantly share code, notes, and snippets.

@davidalpert
Created February 10, 2011 07:15
Show Gist options
  • Save davidalpert/820085 to your computer and use it in GitHub Desktop.
Save davidalpert/820085 to your computer and use it in GitHub Desktop.
FluentValidation.Tests.ConditionTests - Grouping Validation Conditions
private class GroupedWhenConditionValidator : ExpressiveValidator<Person>
{
public GroupedWhenConditionValidator()
{
When(x => x.Id != 0)
.Check(RuleFor(x => x.Age).GreaterThan(4))
.Check(RuleFor(x => x.Discount).Equal(10m));
}
}
[Test]
public void Grouped_condition_can_ignore_mutiple_rules_when_predicate_fails()
{
var validator = new GroupedWhenConditionValidator();
var result = validator.Validate(new Person());
result.Errors.Count.ShouldEqual(0);
}
[Test]
public void Grouped_condition_can_apply_to_mutiple_rules_when_predicate_passes()
{
var validator = new GroupedWhenConditionValidator();
var result = validator.Validate(new Person() { Id = 1001 });
result.Errors.Count.ShouldEqual(2);
}
public class ExpressiveValidator<T> : AbstractValidator<T>
{
public GroupedConditionValidator<T> When(Func<T, bool> predicate)
{
return new GroupedConditionValidator<T>().When(predicate);
}
public GroupedConditionValidator<T> Unless(Func<T, bool> predicate)
{
return new GroupedConditionValidator<T>().Unless(predicate);
}
}
public class GroupedConditionValidator<T>
{
Func<T, bool> whenPredicate;
Func<T, bool> unlessPredicate;
public GroupedConditionValidator()
{
whenPredicate = x => true;
unlessPredicate = x => false;
}
public GroupedConditionValidator<T> When(Func<T, bool> predicate)
{
this.whenPredicate = predicate;
return this;
}
public GroupedConditionValidator<T> Unless(Func<T, bool> predicate)
{
this.unlessPredicate = predicate;
return this;
}
public GroupedConditionValidator<T> Check<TProperty>(IRuleBuilderOptions<T, TProperty> builderOptions)
{
builderOptions.When(whenPredicate).Unless(unlessPredicate);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment