How can I make the required property of the DateTime model?

I have a model that has a datetime property and I want to make sure that in the view the form cannot be submitted unless this editor is relevant.

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 need to use javascript on the page?

or is there another solution?

Update -

When I remove the date editor, I get the following in the editor window:

mm/dd/yyyy

      

when i post this does it count as null or what? If the DateTime nullable property didn't fix my problem, then the validation fails when I submit a form that has mm / dd / yyyy for the date

+3


source to share


1 answer


Your problem is that it DateTime

always matters.

You need to do this with a null value DateTime

:



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

      

Now your property will be null if there is no value and your attribute Required

will behave as expected.

+12


source







All Articles