Source link:
Validating multiple properties with FluentValidation | The Codetripper (wordpress.com)
public class FooBarRequestValidator : AbstractValidator<FooBarRequest> { private readonly IRepository repository; public FooBarRequestValidator(IRepository repository) { this.repository = repository; RuleFor(x => x.Foo) .Must(NotAlreadyHaveABar) .WithMessage("You already have a bar for this foo."); } private bool NotAlreadyHaveABar(FooBarRequest instance, string foo) { return !repository.GetAll<FooBar>() .Any(x => x.Foo == foo && x.Bar == instance.Bar); } }
The trick is using the overload of Must()
that takes a Func<T, TProperty, bool>
predicate: that gives you access to the whole instance for your validating pleasure. Here, in NotAlreadyHaveABar()
I can access Bar
even though the rule is for the Foo
property.