Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a DateTime model property required?

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

like image 808
duxfox-- Avatar asked Nov 19 '14 19:11

duxfox--


1 Answers

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.

like image 104
Ant P Avatar answered Oct 16 '22 04:10

Ant P