Date formatting using data annotation not working
10,621
Solution 1
Before DataFormatString
try adding ApplyFormatInEditMode = true
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
Solution 2
You need to include ApplyFormatInEditMode=true in the DisplayFormat attribute
Solution 3
public string StartDate
{
get { return (startDateTime ?? new DateTime(1000, 01 ,01 )).ToString("G", DateTimeFormatInfo.InvariantInfo); }
}
try other formats if that doesnt suit you
Related videos on Youtube
Author by
Arno 2501
I'm a sotware engineer building software for the web for more than 10 years.
Updated on September 15, 2022Comments
-
Arno 2501 over 1 year
I have this model with the following data annotation because I want to handle the date in this format : dd.MM.yyyy
[DataType(DataType.Date)] [DateRange(ErrorMessageResourceName = "DateBetween", ErrorMessageResourceType = typeof(WizardStrings))] [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")] public DateTime? BirthDate1 { get; set; }
In the view :
@Html.EditorFor(model => model.BirthDate1 ) @Html.ValidationMessageFor(model => model.BirthDate1)
MVC still render this date with the following format : dd/MM/yyyy it seems like it doesn't take my data annotation into account.
See the rendered HTML :
<input class="text-box single-line valid" data-val="true" data-val-required="La date de naissance est requise!" id="BirthDate1" name="BirthDate1" type="text" value="**9/9/1999 12:00:00 AM**">