MVC 3验证不同类中的2个字段

时间:2012-06-30 23:34:53

标签: asp.net-mvc validation viewmodel

我有一个带有2个对象的viewmodel

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

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

ViewModel包含这两个对象

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

1 个答案:

答案 0 :(得分:1)

使用FluentValidation.NET和带有数据注释的PITA完全无聊的场景。

所以这里有一些简单的步骤:

  1. 安装FluentValidation.MVC3 NuGet包
  2. Application_Start注册FV提供商:

    FluentValidationModelValidatorProvider.Configure();
    
  3. 设计您的视图模型(注释:这不是纯粹的视图模型,纯视图模型不应该对域模型进行任何引用,但为了本演示的目的,我将保留这种方式):< / p>

    [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>
    }