tsohtan
tsohtan

Reputation: 850

ASP.Net MVC Datepicker ignore DataFormatString

I have problem display the date in correct format from viewmodel and also the validation not work as well refer to the image

enter image description here.

As i've seen many post mentioned they managed to solved it without needed to set dateformat in client-side. So I NOT wish to set the date format in client-side which mean via jQueryUI datepicker or any method use to format in client-side. But no matter what i tried it seem not taking the format from the ViewModel.

And i knew this question had been posted long time in here, but nothing seem to work to me. Here are the list I had tried but none of them is work to me
Unable to set datetime format in MVC 4 using data annotations
-- Not sure why it's work as i tried date and datetime in data annotation

Validate DateFormat In Mvc
--> tried but still not work

Jquery dd/MM/yyyy date format validation --> is seem overkill to me to include jquery-ui-i18n.js and i don't want to set in client-side.

So anyone can advise what i've missed out? Or Can i say DataFormatString is completely useless without do extra work in client-side?

This is my viewModel

public class DateModel
{
    [Display(Name = "StartDate")]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yy}")]
    public Nullable<DateTime> StartDate { get; set; }

    [Display(Name = "EndDate")]
    [DataType(DataType.DateTime)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yy}")]
    public Nullable<DateTime> EndDate { get; set; }


}

My View

<div class='editor-field'>
    @Html.EditorFor(model => model.StartDate)
    @Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class='editor-label'>
    @Html.LabelFor(model => model.EndDate)
</div>
<div class='editor-field'>
    @Html.EditorFor(model => model.EndDate)
    @Html.ValidationMessageFor(model => model.EndDate)
</div>

Upvotes: 0

Views: 724

Answers (1)

John Prado
John Prado

Reputation: 804

You need to use a jquery globalize plugin in order to adjust the patterns of unobtrusive validation.

Install using nuget Install-Package jquery-globalize or donwload the plugin here.

Include the Globalize.js and ./cultures/globalize-culture[your-culture].js scripts in your bundle.

Use the javascript code bellow in your view or script file:

Globalize.culture("[your-culture]");
$.validator.methods.date = function(value, element) {
    return this.optional(element) || Globalize.parseDate(value);
};

Upvotes: 0

Related Questions