user1869870
user1869870

Reputation: 473

ASP.NET MVC3 - RAZOR - Date format validation not working

I'm new to MVC3 - and cannot figure out why the Date format validation is not working on client-side i.e., if I manually change the text box and input an invalid format date. I'm using jQuery date picker for this field. The strange thing is that the Required Field Validation is working.

Can someone please let me know what's wrong with this code?

Thanks!

VIEWMODEL

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date, ErrorMessage="Please enter a valid date in the format dd/mm/yyyy")]
    [Required]
    public DateTime ADate { get; set; }

VIEW

        @Html.TextBox("ADate", Model.ADate.ToShortDateString(), new { @class = "ADate" })
        @Html.ValidationMessageFor(model => model.ADate, "*")

Upvotes: 2

Views: 1254

Answers (2)

Bishnu Paudel
Bishnu Paudel

Reputation: 2079

You can use underlying TextBoxFor() and specify a class name

@Html.TextBoxFor(model => model.ADate, new { @class = "ADate" }) 

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

DataType and DisplayFormat only works when using DisplayFor or EditorFor, and not with a TextBox. You can't set a class name with EditorFor, however.

Upvotes: 1

Related Questions