Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

asp.net mvc - Error in date validation MVC

My model class property looks like this

   public DateTime PurchaseDate { get; set; }

and inside view

 @Html.TextBoxFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

and I am giving a date like this in form

19/06/2015

But it gives validation message and not allows page to be submitted, message is like this

The field PurchaseDate must be a date.

if I give date in mm/dd/yyyy format it works. Can anyone point out what I am doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to explicitly set the expected date format for your model property then you can do this using the DisplayAttribute

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PurchaseDate { get; set; }

Otherwise, the current culture of the server would be used (which in your case happens to be MM/dd/yyyy).


It appears that in order for client-side validation to respect the DataFormatString we need to use EditorFor in place of TextBoxFor

 @Html.EditorFor(model => model.PurchaseDate, new { @class = "form-control date-picker" })
 @Html.ValidationMessageFor(model => model.PurchaseDate)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...