使用FluentValidation for .NET有条件地执行规则

时间:2014-02-20 01:27:46

标签: c# asp.net-mvc fluentvalidation

我正在使用FluentValidation for .NET

我有这三条规则:

RuleFor(customer => customer.Name).NotEmpty();
RuleFor(customer => customer.Phone).NotEmpty();
RuleFor(customer => customer.Birthday).NotEmpty();

我只想在其他三个人成功验证后才能执行这个。

RuleFor(customer => customer).Must(IsUnique).WithMessage("...");

我的要求是不使用像here之类的链接验证器,因为如果前一个验证器未通过验证,则不会评估前三个验证器。

我想要的是如果前三个中的一个是空的,则向用户显示必需的字段。如果这三个都不是空的,那么我想验证最后一个。

1 个答案:

答案 0 :(得分:2)

RuleFor(customer => customer)
.Must(IsUnique)
.WithMessage("...")
.When(x => !string.IsNullOrEmpty(x.Name) && !string.IsNullOrEmpty(x.Phone) &&!string.IsNullOrEmpty(x.Birthday));