ror*_*yok 4 c# fluentvalidation asp.net-mvc-3
我在ASP.Net MVC 3项目中设置了FluentValidation.我有一个有两个输入的表格.两者都可以是空白,但不能同时为空.
这就是我所拥有的:
RuleFor(x => x.username)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.email) == true)
.WithMessage("Please enter either a username or email address")
Run Code Online (Sandbox Code Playgroud)
这正确地将错误直接放在我的用户名字段上方.但是,当两个字段都留空时,我更喜欢验证摘要来显示消息
有没有办法做到这一点?我一直在想我可以在模型中创建一个未使用的字段并将错误放在那里(如果其他两个是空白的话),
RuleFor(x => x.unused_field)
.NotEmpty()
.When(x => string.IsNullOrEmpty(x.email) == true && string.IsNullOrEmpty(x.username) == true)
.WithMessage("Please enter either a username or email address")
Run Code Online (Sandbox Code Playgroud)
但这感觉就像是一种尴尬的方式.有没有办法可以在验证摘要中添加消息?
我能找到的唯一参考是这个.
现在,如果你的模型很简单并且这个规则是唯一的那么,那么这个规则就足够了:
RuleFor(x => x)
.Must(x => !string.IsNullOrWhiteSpace(x.Email) || !string.IsNullOrWhiteSpace(x.UserName))
.WithName(".") // This adds error message to MVC validation summary
.WithMessage("Please enter either a username or email address");
Run Code Online (Sandbox Code Playgroud)
只需添加@Html.ValidationSummary()到您的视图中就可以了.
但是如果你要在你的模型上加入更多规则,那么据我所知,我只能想到一种"hacky"方式:
在你的控制器动作中添加:
if (!ModelState.IsValid)
{
if (ModelState["."].Errors.Any())
{
ModelState.AddModelError(string.Empty, ModelState["."].Errors.First().ErrorMessage);
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
这将从"."属性向模型属性添加第一条错误消息(根据您的需要进行调整).此外,您还必须@Html.ValidationSummary(true)在验证摘要中仅显示模型级错误.
第三种选择:将规则添加到unused_property并@Html.ValidationSummaryFor(x => x.unused_property)用作验证摘要