Search code examples
c#.netactionfluentvalidation

How can I create a RuleSet with a .NET FluentValidation InlineValidator?


I'm creating an InlineValidator (from the FluentValidation nuget package/library).

var validator = new InlineValidator<Person>;
validator.RuleFor(x => x.Surname).NotNull();
validator.RuleSet("someRuleSet", () => {
    // ?????
            });

When I try to call the RuleSet method in there, it seems to not compile.

How can I create a RuleSet against an InlineValidator please ?

Here's the example ruleset i'm trying...

.RuleSet("someRuleSet", () =>
{
    RuleFor(x => x.Name).NotNull();
    RuleFor(x => x.Age).NotEqual(0);
}

Solution

  • You can't access RuleFor as a global method, it sits on the InlineValidator. Here's an example of how you can add a RuleSet and then validate against it:

    // Setup the inline validator and ruleset
    var validator = new InlineValidator<Person>();
    
    validator.RuleSet("test", () =>
    {
        validator.RuleFor(x => x.Name).NotNull();
        validator.RuleFor(x => x.Age).NotEqual(0);
    });
    
    var person = new Person();
    
    // Validate against the RuleSet specified above
    var validationResult = validator.Validate(person, ruleSet: "test");    
    
    Console.WriteLine(validationResult .IsValid); // Prints False