我的流利验证如下:
RuleFor(o => o.zipCode)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Must((o, zipCode) => CountryInfoMap.IsValidPostalCode(zipCode, "AT"))
.When(o => !string.IsNullOrEmpty(o.ZipCode))
.WithMessage(ErrorDto.ToModelMessage(ErrorCode.InvalidZipCode, $"{{PropertyName}} '{{PropertyValue}}' is invalid for specified country."));
当没有传递任何zipCode
值时,它仍将调用方法CountryInfoMap.IsValidPostalCode
,这是一个静态方法。为什么在它为空的第一个失败时不停止?
答案 0 :(得分:1)
删除When
:
RuleFor(o => o.zipCode)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.Must((o, zipCode) => CountryInfoMap.IsValidPostalCode(zipCode, "AT"))
.WithMessage(ErrorDto.ToModelMessage(ErrorCode.InvalidZipCode, $"{{PropertyName}} '{{PropertyValue}}' is invalid for specified country."));
您已经在验证它,因为它不为空。