如何使用 .NET FluentValidation InlineValidator 创建规则集?

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

我正在创建一个 InlineValidator(来自 FluentValidation nuget package/library)。

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

当我尝试调用那里的 RuleSet 方法时,它似乎无法编译。

请问如何针对 InlineValidator 创建规则集?

这是我正在尝试的示例规则集...

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

您无法将 RuleFor 作为全局方法访问,它位于 InlineValidator 上。下面是一个示例,说明如何添加 RuleSet 然后对其进行验证:

// 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