我正在使用 mvc4 的流畅验证
在我的模型中,我有一个列表:
public List<int> TransDrops { get; set; }
我在 View 中为列表中的每个项目创建文本框。
我想随后确保每个字段都已填写。(非空/空)
OrderDetailsViewModelValidator 是模型上的验证器,我需要什么?
谢谢
最佳答案
首先你必须为集合项使用nullable整数类型,否则空文本框将被绑定(bind)到零值,这使得无法区分空文本框和填充零.
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 个项目。
关于c# - 流利的验证集合项不为空/空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22786979/