I need to verify that a datetime is valid with Validation.
Razor MVC3
Class
[Range(typeof(DateTime), "1/1/1930", "1/1/2112",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime DOB { get; set; }
Edit View form
<span class="editor-field">
@Html.EditorFor(model => model.DOB)
@Html.ValidationMessageFor(model => model.DOB)
The validation catches an invalid date but will not clear the error when a valid date is entered, so the form is hung. Does anyone know a working way to use Validation to check if a datetime is valid?
Thanks, Joe
Updated Controller action
[HttpPost]
public ActionResult Create(Talent talent)
{
talent.Modified = talent.Created = DateTime.Now;
if (talent.DOB < DateTime.Now.AddYears(-100) || talent.DOB > DateTime.Now)
{
talent.DOB = DateTime.Parse("0001/01/01"); talent.Skill = "changed";
return View(talent); }
Final Controller and Post Action
string errorMessageDOB = "DOB is out of range, it needs to be between " + DateTime.Now.AddYears(-100).ToShortDateString()
+ " and " + DateTime.Now.ToShortDateString() + ".";
//
// POST: /Talent/Create
[HttpPost]
public ActionResult Create(Talent talent)
{
talent.Modified = talent.Created = DateTime.Now;
if (talent.DOB < DateTime.Now.AddYears(-100) || talent.DOB > DateTime.Now)
{ ModelState.AddModelError(string.Empty, errorMessageDOB); }