DotnetSparrow
DotnetSparrow

Reputation: 27996

DisplayFormat Dataannotation not working

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 ?

Upvotes: 0

Views: 5784

Answers (2)

Stephen
Stephen

Reputation: 1737

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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>

Upvotes: 4

Related Questions