I have tried:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}", ConvertEmptyStringToNull = true)]
[Required(AllowEmptyStrings = true)]
public DateTime? BirthDateFrom { get; set; }
and
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[Required]
public DateTime? BirthDateFrom { get; set; }
and all combinations with and without ConvertEmptyStringToNull
and AllowEmptyStrings
.
In view, I have:
@Html.EditorFor(m => m.BirthDateFrom)
I can submit form with valid date, but with empty string in that field, it just goes red and the form cannot be submitted. How to allow HTML form submission with null or empty string value in required nullable DateTime?
The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
DateTime itself is a value type. It cannot be null.
It seems to me that simply removing the [Required]
annotation entirely would meet your requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With