I have the following class:
public class Post
{
[DataType(DataType.Date, ErrorMessage="Please fill in a valid date.")]
[RegularExpression(@"^\d{1,2}\/\d{1,2}\/\d{4}$", ErrorMessage="Fill in a valid date.")]
public DateTime? PublishDate { get; set; }
}
and in my Edit action I have it like this
[HttpPost]
public ActionResult Edit(Post post)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(post);
}
}
But my ModelState is always invalid. How come? How can I solve this?
I also posted here: http://forums.asp.net/t/1663783.aspx/1?MVC3+how+to+check+datetime+on+model+with+unobtrusive+javascript+.
Update: I found that there is indeed an error via:
ModelState.Values.Select(x => x.Errors);
But how can I find out how it gets there? And more important, how 开发者_如何学Gocan I solve it?
Your regular expression does not work with the date that you enter. I would simply remove it since the DateTime
struct will not be assigned if the date can't be parsed by the model binder.
精彩评论