19

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

4
  • DateTime isn't going to be null. What happens if you change the type to DateTime?? Commented Nov 19, 2014 at 19:15
  • @Jonesy what do you mean? It's already DateTime Commented Nov 19, 2014 at 19:16
  • adding a question mark after a type makes it nullable, so DateTime? is a nullable DateTime Commented Nov 19, 2014 at 19:17
  • I see, I'm trying it now, thanks! Commented Nov 19, 2014 at 19:18

1 Answer 1

45

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
ah, Model.IsValid might be it, forgot about that, thanks for pointing it out!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.