Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...