16

I have a model that has a datetime property and I want to make sure that in the view, the form can't be submitted unless that editor for has a value.

employee {
 [DataType(DataType.Date)]
 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
 [Required] // <- this isn't doing anything for me???
 public DateTime DateOfBirth {get;set;}
}

is there an annotation I can use for this or do I have to use javascript in the page?

or is there another solution?

Update -

When I clear out the date editor, I get the following in my editor box:

mm/dd/yyyy

when I submit this, does this count as null or what? Making the DateTime property nullable didn't fix my issue, theres no validation taking place when I submit a form that has mm/dd/yyyy for the date

Ant P
  • 24,820
  • 5
  • 68
  • 105
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

1 Answers1

40

Your problem is that DateTime always has a value.

You'll need to make it a nullable DateTime:

[Required]
public DateTime? DateOfBirth { get; set; }

Now your property will be null when no value is present and your Required attribute will behave as expected.

Ant P
  • 24,820
  • 5
  • 68
  • 105
  • @AbdulAhmad Your question doesn't have enough information in it to answer further - this is the cause of your problem, if you are still having problems, the cause is elsewhere. You now need to debug your action methods and inspect the model property, ensure that you are checking `Model.IsValid` and so on. If you encounter *other* problems, ask about them as new questions. – Ant P Nov 19 '14 at 19:28
  • ah, Model.IsValid might be it, forgot about that, thanks for pointing it out! – Abdul Ahmad Nov 19 '14 at 19:31