使用MVC3的C# FluentValidation规则for ()检查组合是否有值的正确方法是什么?
我有一套3个组合框的出生日期
@Html.DatePickerDropDowns(Html.FieldNameFor(x => x.DateOfBirthDay),
Html.FieldNameFor(x => x.DateOfBirthMonth),
Html.FieldNameFor(x => x.DateOfBirthYear),
DateTime.Now.Year - 110,
DateTime.Now.Year,
Model.DateOfBirthDay,
Model.DateOfBirthMonth,
Model.DateOfBirthYear)
@Html.ValidationMessageFor(model => model.DateOfBirthDay)
@Html.ValidationMessageFor(model => model.DateOfBirthMonth)
@Html.ValidationMessageFor(model => model.DateOfBirthYear)每个组合显示“日”、“月”或“年”。
他们每个人都有自己的相关列表。
因此,我想检查用户是否选择了0..31中的一个值。
RuleFor(x => x.DateOfBirthDay).NotEqual(0).WithMessage("Day is required");
RuleFor(x => x.DateOfBirthMonth).NotEqual(0).WithMessage("Month is required");
RuleFor(x => x.DateOfBirthYear).NotEqual(0).WithMessage("Year is required");例如,DateOfBirthDay HTML输出组合如下所示:
"0" - Day
"1" - 1
"2" - 2
...till 31 当我运行ModelState.IsValid时,它没有发现用户没有接触任何组合值的事实,将索引保留为"0“。
在进阶时谢谢。
发布于 2011-12-16 07:47:10
我不确定"DatePickerDropdowns“是什么,但是FluentValidation对这种情况有特殊的逻辑。使用.NotEmpty(),而不是将Day设置为0,将其保留为空。使用默认DropDownListFor,您可以将选项参数设置为"Day“,这将自动发生。
你写了DatePickerDropDowns帮助器吗?我不会以这种方式实现它。我会使用一个DateTime,然后创建一个为该类型创建3个下拉框的EditorTemplate (如果这是您唯一的DateTime,否则使用UIHint指定一个自定义模板)。
发布于 2011-12-16 05:00:09
//像这样的东西可以工作吗?我假设你正在寻找它是否等于"...“?
string somestring = new string('.',3);
this.RuleFor(x => x.MyComboList).Equals(somestring);//或者
this.RuleFor(x => x.MyComboList).NotEqual(0).WithMessage("..."); https://stackoverflow.com/questions/8526281
复制相似问题