DisplayFormat Dataannotation not working

2019-03-04 13:44发布

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 ?

2条回答
在下西门庆
2楼-- · 2019-03-04 14:23

The DisplayFormat attribute 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:

<tr>
    <td>
        @Html.LabelFor(x => x.DateOfBirth, "Date Of Birth")
    </td>
    <td>
        @Html.EditorFor(x => x.DateOfBirth)
        <br/>
        @Html.ValidationMessageFor(x => x.DateOfBirth)
    </td>
</tr>
查看更多
男人必须洒脱
3楼-- · 2019-03-04 14:30

The LabelFor doesn't have an overload that allows you to set the CSS, you can set the lambda or the Lambda and the text.

When I remove the "new { @class = "lbl" }" part and run your code I get validation working fine.

Edit: Apologies, my initial test was using an EditorFor and my machines culture was set to US, so it worked all fine.

You can set the globalization culture in your webconfig to the correct culture that uses the mm\dd\yyyy eg.

<globalization culture="en-us" />

but this will take effect over the entire website (including the format of numbers, dates, currency, etc) so if this is a limited case, then this might not be the solution for your problem.

查看更多
登录 后发表回答