【问题标题】:fluent validation collection items not null/empty流利的验证集合项不为空/为空
【发布时间】:2014-04-01 13:13:28
【问题描述】:
我正在使用 mvc4 流畅的验证
在我的模型中,我有一个列表:
public List<int> TransDrops { get; set; }
在视图中,我为列表中的每个项目创建文本框。
我想随后确保每个字段都已填写。(非空/空)
OrderDetailsViewModelValidator 是模型上的验证器,我需要什么?
谢谢
【问题讨论】:
标签:
c#
asp.net-mvc
fluentvalidation
【解决方案1】:
首先你必须为集合项使用 nullable 整数类型,否则空文本框将绑定到 zero 值,这使得无法区分空文本框并填充零.
public List<int?> TransDrops { get; set; }
接下来,使用谓词验证器(必须规则):
RuleFor(model => model.TransDrops)
.Must(collection => collection == null || collection.All(item => item.HasValue))
.WithMessage("Please fill all items");
如果您需要防止空集合被成功验证,只需在谓词验证器之前添加NotEmpty() 规则:它检查任何IEnumerable 而不是null,并且至少有1 个项目。
【解决方案2】:
现在有一个更简单的方法,使用RuleForEach:
RuleForEach(model => model.TransDrops)
.NotNull()
.WithMessage("Please fill all items");
确保使用NotNull 而不是NotEmpty,因为 NotEmpty 验证类型的默认值(在这种情况下:int,它是 0)。
您可以在documentation查看更多详细信息