0

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); }
Joe
  • 4,143
  • 8
  • 37
  • 65

1 Answers1

2

You could implement a custom validation attribute as shown in this article.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Stuart writes some great code but that is a lot more complicated then what I wanted and I don't want a date picker for Date of Birth. I added some code to my POST Action (see updated question). It successfully traps an out of range date and updates the DOB and Skill field when I watch it in the debugger but when the view is re-displayed the old values are still there (I was testing to see if setting DOB to 1/1/0001 would kick off the valid date required validation. Skill is there just for testing). Would you have any idea why the edited fields aren't updated in the view? – Joe Mar 23 '12 at 00:00
  • That's might be because HTML helpers are using the value from the ModelState when redisplaying the view and not the values you set in your model. If you want your changes to have effect you need to remove the values from the model state. For example you seem to be attempting to set the `Modified`, `DOB` and `Skill` properties in your action => `ModelState.Remove("Modified"); ModelState.Remove("DOB"); ModelState.Remove("Skill");`. – Darin Dimitrov Mar 23 '12 at 06:52
  • While looking at ModelState found this solution [1]: http://stackoverflow.com/questions/5739362/modelstate-addmodelerror-how-can-i-add-an-error-that-isnt-for-a-property Use ModelState.AddModelError(); See updated POST for code. – Joe Mar 23 '12 at 15:49