ASP.NET Core Web API -如何使用Fluent validation执行条件相对



. NET Core-6 Web API,我使用Fluent Validation有这个验证器:

public CustomerValidator()
{
RuleFor(p => p.NotificationType)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!");
RuleFor(p => p.MobileNumber)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!");
RuleFor(p => p.Email)
.EmailAddress();
}

我想使用以下条件进行验证:

如果NotificationType = 'Email',那么Email应该是必需的

如果NotificationType = 'SMS',则应该需要MobileNumber

如果NotificationType = 'Both',那么Email和MobileNumber应该是必需的

我如何做到这一点?

感谢

您可以在fluentvalidation上使用When()扩展。

https://docs.fluentvalidation.net/en/latest/conditions.html

RuleFor(p => p.MobileNumber)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("{PropertyName} should be not empty. NEVER!")
.When(x => x.NotificationType == "SMS");

最新更新