I have following dataannotation in my model class:
[Required(ErrorMessage = "Required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DateOfBirth { get; set; }
and when I use following in my view, I dont get validation error:
<tr>
<td>@Html.LabelFor(x => x.DateOfBirth, new { @class = "lbl" }, "Date Of Birth") </td>
<td>@Html.TextBoxFor(x => x.DateOfBirth, new { @class = "w100 _dob" })
<br>@Html.ValidationMessageFor(x => x.DateOfBirth)
</td>
</tr>
Can you please suggest the solution ?
The
DisplayFormatattribute has nothing to do with validation. It is used only to format the value when displayed on a view. If you want to validate that the value that is being entered by the user in the corresponding input field you will have to write a custom model binder.And by the way the DisplayFormat attribute is used in conjunction with the Html.EditorFor helper and it has strictly no effect with the Html.TextBoxFor helper which is what you are using: