1

使用 C# FluentValidation Rulefor() for MVC3 检查组合是否具有值的正确方法是什么?

我有一组 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)

每个组合都显示“DAY”或“Month”或“Year”
,并且它们都有各自的相关列表。

所以我想检查用户是否选择了 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”。

先谢谢了。

4

2 回答 2

3

我不确定“DatePickerDropdowns”是什么,但 FluentValidation 对这种情况有特殊的逻辑。使用 .NotEmpty() 而不是将 Day 设置为 0,而是将其留空。使用默认的 DropDownListFor,您可以将选项参数设置为“Day”,这将自动发生。

您是否编写了 DatePickerDropDowns 助手?我不会以这种方式实现它。我会使用单个 DateTime,然后创建一个 EditorTemplate,为这种类型创建 3 个下拉菜单(如果它是您拥有的唯一 DateTime,否则使用 UIHint 指定自定义模板)。

于 2011-12-15T23:47:09.963 回答
0

//这样的东西会起作用吗..?我假设您正在寻找它是否等于 "..." ?

string somestring = new string('.',3);
this.RuleFor(x => x.MyComboList).Equals(somestring);

//或者

this.RuleFor(x => x.MyComboList).NotEqual(0).WithMessage("..."); 
于 2011-12-15T21:00:08.830 回答