问题描述
我对FluentValidation有疑问。我目前有以下验证:
RuleFor(x => x.value)
.NotNull()
.WithMessage("This field is mandatory.");
如何添加条件,以便仅在x.mandatory属性的值等于true时才进行验证?
解决方法
FluentValidation支持When
和Unless
方法的条件。有关详细信息,请参见文档中的此页面https://docs.fluentvalidation.net/en/latest/conditions.html
通过在NotNull之后将调用链接到When
,可以实现您的目标:
RuleFor(x => x.value)
.NotNull()
.When(x => x.mandatory)
.WithMessage("This field is mandatory.");