user576914 user576914 - 9 days ago 6
C# Question

RequiredAttribute for DateTime if field empty or wrong

The

RequiredAttribute
works for
string
but not
DateTime
. For example:

[Required]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }

[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}", ConvertEmptyStringToNull = false)]
public DateTime Birthdate { get; set; }


If
Name
is empty the Validation shows error, but if
Birthdate
is empty then nothing happens. I looked at:

ASP MVC 5 Client Validation for Range of Datetimes

and

MVC Model Range Validator?

but still doesn't work for the
DateTime

Answer

Datetime is a struct, structs are "value type", not "reference type", so their default value is not null, for datetime it is "1/1/0001 12:00:00 AM", int have it's default value as 0.

string type is a "reference type", all reference type have their default value as null.

so if you want to check if a value type is null you should create it as nullable.

like this:

public DateTime? Birthdate { get; set; }

Or

public Nullable<DateTime> Birthdate { get; set; }
Comments