ModelState.IsValid is always true
We ran into a snag with using the new default Data Annotations Validation in ASP.Net MVC 2.0 Preview 2. Maybe it isn’t a snag, but it is not the behavior I would have expected.
Take the following model:
public class Person
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Required (ErrorMessage = "Required")]
public string EmailAddress { get; set; }
}
Pretty straight forward, but if you post this form:
<form action="/person/edit" method="post">
<input type=hidden name="id" id="id" value="" />
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" />
</form>
To this controller action:
[HttpPost] public virtual ActionResult Edit(Person data)
{
if (!ModelState.IsValid) throw new ItBrokeException();
return View();
}
Personally, I would expect every post of that form to show up as invalid, but infact, it is always true. Add the following input to the form and it works.
<input type="text" id="emailaddress" name="emailaddress" /> <br/>
After that, the ModelState.IsValid returns false, like it should.
Comments(2)
Agreed, I found this today also. I posted an issue with the MVC team on codeplex and referenced your blog. Thanks.
@Wayne It appears the client validation also has a similar expectation, that you explicitly mention you want validation on each item. http://fooberry.com/2009/12/15/asp-net-mvc-2-0-data-annotations-validation-doesnt-emit-correct-json/