如何使用.NET FluentValidation InlineValidator创建RuleSet?

时间:2016-01-08 04:07:44

标签: c# .net action fluentvalidation

我正在创建InlineValidator(来自FluentValidation nuget包/库)。

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

1 个答案:

答案 0 :(得分:2)

您无法访问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