选择列表值的FluentValidation

时间:2011-08-25 16:31:13

标签: .net asp.net-mvc asp.net-mvc-3 fluentvalidation

如何验证值为0的选择列表?

我试过以下

RuleFor(x => x.ProductId).Equal(0).WithMessage(required);
RuleFor(x => x.ProductId).NotEqual(0).WithMessage(required);
RuleFor(x => x.ProductId).GreaterThan(0).WithMessage(required);
RuleFor(x => x.ProductId).GreaterThan(0).When(x => x.ProductId < 1).WithMessage(required);
//etc.

对于“选择...”,我的选择列表的值为“0”。如果我在表单中选择该值,则ModelState.IsValid会抛出错误('not expected range'),或者如果我注释掉ModelState.IsValid,则会将值0发布到db。无论哪种方式都没有进行验证。我的所有其他字段都是字符串,int和布尔的混合工作正常并且可以正确验证。

注意:ProductId是我的模型和视图模型中的int。

忘记..

1 个答案:

答案 0 :(得分:1)

我解决了这个问题。这是一个我希望从未问过的问题。解决方案是一个错误的喜剧,但我将分享我在此过程中发现的内容。

简短的回答是:

RuleFor(x => x.ProductId).GreaterThan(0).WithMessage(required);

问题在于我的控制器和(令人尴尬)我的观点。

  1. 我忘了为ProductId添加validationmessage。但这并没有完全解决问题。
  2. 我的控制器看起来像这样。
  3. 
    [HttpPost]
    public ActionResult Update(ProductModel model)
    {
      if(!ModelState.IsValid)
          throw new ArgumentExpection();
    //etc.
    }
    

    我最初测试我的模型以使用Automapper,一旦我实现了验证,我忘了删除ArgumentException。

    这样做并没有让我的验证规则成为现实。当然它从未经过验证,因为控制器被告知抛出关于ModelState的错误而不是回发ACTUAL验证错误。 Dohhh!

    [HttpPost]
    public ActionResult Update(ProductModel model)
    {
      if(!ModelState.IsValid)
         return View(model);//pssst! the validation error is in here.
    //etc.
    }
    

    我现在对事物的顺序有了更好的理解。希望这可以帮助那些像我一样愚蠢的人。