FluentValidation for select list values
How do I validate a select list for a value of 0?
I have tried the following
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)开发者_StackOverflow.WithMessage(required);
//etc.
My select list has a value of '0' for 'Select...'. If I choose that value in my form, either the ModelState.IsValid throws an error ('not expected range') or if I comment out the ModelState.IsValid then a value of 0 gets posted to the db. Either way no validation is occurring. All my other fields which are a mix of strings, int, and boolean work fine and validate correctly.
Note: ProductId is a int in my model and view model.
Lost..
I solved the problem. This is a question I wished I had never asked. The solution was a comedy of errors but I will nonetheless share what I discovered along the way.
The short answer is:
RuleFor(x => x.ProductId).GreaterThan(0).WithMessage(required);
The problem was in my controller and (embarrassing enough) my view.
- I forgot to add my validationmessagefor ProductId. But this did not solve the problem entirely.
- My controller looked like this.
[HttpPost]
public ActionResult Update(ProductModel model)
{
if(!ModelState.IsValid)
throw new ArgumentExpection();
//etc.
}
I originally was testing my model to work with Automapper and once I implemented validation I forgot to remove the ArgumentException.
What this did was never give my validation rule the light of day. Of course it never validated because the controller was told to throw an error ABOUT the ModelState instead of post back the ACTUAL validation error. Dohhh!
[HttpPost]
public ActionResult Update(ProductModel model)
{
if(!ModelState.IsValid)
return View(model);//pssst! the validation error is in here.
//etc.
}
I do have a better understanding of the order of things now. Hope this helps someone else who is dumb as I was.
精彩评论