How can I make a DateTime model property required?

13,397

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.

Share:
13,397
Abdul Ahmad
Author by

Abdul Ahmad

Stuff that I do: node - express - react - angular - sequelize react native ruby on rails asp.net-mvc - c# - java - python design: html - css - sass iOS

Updated on July 17, 2022

Comments

  • Abdul Ahmad
    Abdul Ahmad almost 2 years

    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

    • Jonesopolis
      Jonesopolis over 9 years
      DateTime isn't going to be null. What happens if you change the type to DateTime??
    • Abdul Ahmad
      Abdul Ahmad over 9 years
      @Jonesy what do you mean? It's already DateTime
    • Jonesopolis
      Jonesopolis over 9 years
      adding a question mark after a type makes it nullable, so DateTime? is a nullable DateTime
    • Abdul Ahmad
      Abdul Ahmad over 9 years
      I see, I'm trying it now, thanks!
  • Ant P
    Ant P over 9 years
    @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.
  • Abdul Ahmad
    Abdul Ahmad over 9 years
    ah, Model.IsValid might be it, forgot about that, thanks for pointing it out!