DisplayFormat Dataannotation not working

纵然是瞬间 提交于 2019-12-20 07:29: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 ?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/6921928/displayformat-dataannotation-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!