1

我有一个视图模型,里面有 2 个对象

class trip
{
    public DateTime returnedDate {get;set;}
    ....
}

class personData
{
   public DateTime PassportExpDate {get;set;}
    ....
}

ViewModel 包含这两个对象

如何实现验证,以便 PassportExpDate > returnedDate

4

1 回答 1

1

使用FluentValidation.NET和带有数据注释的 PITA呈现完全微不足道的场景。

所以这里是简单的步骤:

  1. 安装FluentValidation.MVC3NuGet 包
  2. 在以下位置注册 FV 提供者Application_Start

    FluentValidationModelValidatorProvider.Configure();
    
  3. 设计你的视图模型(备注:这不是一个纯视图模型,纯视图模型不应该对领域模型进行任何引用,但出于本演示的目的,我将保留它):

    [Validator(typeof(MyViewModelValidator))]
    public class MyViewModel
    {
        public Trip Trip { get; set; }
        public PersonData PersonData { get; set; }
    }
    
  4. 现在为视图模型定义相应的 FV 验证器:

    public class MyViewModelValidator : AbstractValidator<MyViewModel>
    {
        public MyViewModelValidator()
        {
            RuleFor(x => x.Trip.ReturnDate)
                .LessThan(x => x.PersonData.PassportExpDate)
                .WithMessage("You wanna get arrested?");
        }
    }
    
  5. 控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel
            {
                Trip = new Trip
                {
                    ReturnDate = new DateTime(2012, 8, 13)
                },
                PersonData = new PersonData
                {
                    PassportExpDate = new DateTime(2012, 8, 12)
                }
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    
  6. 看法:

    @model MyViewModel
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Trip.ReturnDate)
            @Html.EditorFor(x => x.Trip.ReturnDate)
            @Html.ValidationMessageFor(x => x.Trip.ReturnDate)
        </div>
        <div>
            @Html.LabelFor(x => x.PersonData.PassportExpDate)
            @Html.EditorFor(x => x.PersonData.PassportExpDate)
            @Html.ValidationMessageFor(x => x.PersonData.PassportExpDate)
        </div>
    
        <button type="submit">OK</button>
    }
    
于 2012-07-01T06:05:16.500 回答