例如,FluentValidation验证用户输入的空电子邮件地址。
我链接了两个函数,但它跳过.NotEmpty().WithMessage()
并跳转到下一个EmailAddress().WithMessage()
。
RuleFor(r => r.EmailAddress)
.NotEmpty().WithMessage("Email address is required.")
.EmailAddress().WithMessage("Email address is not valid.");
为什么错误讯息是"Email address is not valid."
而第一个链是"Email address is required."
?
答案 0 :(得分:3)
这是因为即使第一个规则失败,也始终验证最后一个条件。尝试设置CascadeMode
,如the documentation中所述,如下所示:
RuleFor(r => r.EmailAddress)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("Email address is required.")
.EmailAddress().WithMessage("Email address is not valid.");