3

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);
}

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

For those who are using FluentValidation version 10.0 or above, according to the 10.0 Upgrade Guide, the Validation/ValidationAsync extension methods with the ruleSet argument which is a string type had been removed.

validator.Validate(instance, ruleSet: "someRuleSet");

// For multiple rule sets
// validator.Validate(instance, ruleSet: "someRuleSet,AnotherRuleSet");

The migration to be taken is by providing the Action<ValidationStrategy<T>> instance by defining the rule sets as the second argument:

validator.Validate(instance, v => 
{
    v.IncludeRuleSets("someRuleSet");

    // For multiple rule sets
    // v.IncludeRuleSets("someRuleSet", "AnotherRuleSet");
});

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.