3

I've saw about 1k posts on this, but I must have missed something.

Basically, I am trying to use dd/MM/yyyy format in my site, problem occurs at validation.

I've a ViewModel:

   public class LoanBaseViewModel
    {
        public int LoanId { get; set; }

        [Required]
        [DataCompareValidation("ReturnDate", ErrorMessage = "Return date should be later than loan date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime LoanDate { get; set; }


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

In my EditorTemplate I've This:

@model System.Nullable<System.DateTime>
@if (Model.HasValue)
{
    @Html.TextBox("", String.Format("{0:dd/MM/yyyy}", Model.Value), new { @class = "jq-date" })
}
else
{
    @Html.TextBox("", "", new { @class = "jq-date" })
}

On page Load I attach a Jquery DatePicker on the jq-date.

 $("#loanForm").find(".jq-date").datepicker({ dateFormat: 'dd/mm/yy' });

Display works fine, but every time i tried to save, it tells me date is not in correct format if I use a dd/MM/yyyy date.

Any idea why?

I've been trying for like one hour and it's driving me insane!

Thanks for your time

Tom

Edit: didn't work better What is really weird is that it does work on my laptop, but not in my desktop both of them are display date in dd/MM/yyyy, my laptop accepts 25/08/2013 but not my desktop...

Edit: Solution is here: stackoverflow.com/a/13528769/1741443.

Tom
  • 944
  • 1
  • 14
  • 26

4 Answers4

2

Its a bit difficult to answer definitively without seeing how you have formatted the jQuery datepicker. The default return for jq-date is mm/dd/yy (all numerical data).

The formatting you've set are field-related formats; fields that are waiting for jQuery to pass it the date in a format it is expecting. The field-level formatting is not applied to jQuery - that's a separate formatting requirement.

  1. I suggest you turn ApplyFormatInEditMode off / false and see if the date field works properly with datepicker.

  2. If that does not work then move onto formatting the jq-date according to the below.

For more info on the Datepicker formatting options check the API documentation or go to this page

I'm sure you have already referenced both jQuery and Jquery UI on the page but you should include the following customisation for that datepicker:

<script type="text/javascript">
$(function(){ 
$('.datepicker').datepicker({dateFormat: 'dd-M-yy'});
 });
</script>

In the example above the jQuery format returns dd - two digit day of the month, M - short name for the month, and yy - four digit year.

Hope that helps.

Springbokkie
  • 188
  • 1
  • 11
  • Hi, thanks for your answer. I did use the init date picker like this: $("#loanForm").find(".jq-date").datepicker({ dateFormat: 'dd/mm/yy' }); I m not sure it's the date picker that raise the error, but more like the data validation at post. – Tom Aug 04 '13 at 20:19
  • Failing which, have you thought of changing your culture settings from en-US to **en-GB**, which will swing the date around for you immediately. [http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx] references the fact that the format methods are shown in the default example for en-US i.e. mm/dd/yy. – Springbokkie Aug 04 '13 at 20:47
  • Tried the en-GB didn't make difference on my desktop. But my laptop is accepting dd/MM/yyyy dates. – Tom Aug 05 '13 at 19:27
  • @Tom have you tried a different browser on your desktop to test if its a Chrome/IE/Firefox/Safari/Opera issue? – Springbokkie Aug 05 '13 at 19:57
  • Alright, you win, on my desktop i debug on Chrome, on Laptop, it's Firefox.. Firefox works fine, Chrome is the culprit... – Tom Aug 06 '13 at 15:48
  • checking this post: http://stackoverflow.com/questions/6906725/unobtrusive-validation-in-chrome-wont-validate-with-dd-mm-yyyy – Tom Aug 06 '13 at 16:15
  • 1
    Alright to fix it i used this solution: http://stackoverflow.com/a/13528769/1741443. Seems to be working on chrome, i'll test FF Tomorrow. Thanks! – Tom Aug 06 '13 at 17:48
2

Assuming your servers culture is not set to the cultural format you want to use, you need to set the globalization settings in your web.config to the culture you plan on using. I don't know where you're from, but i'll assume the UK. So you can set

 <globalization culture="en-GB"/>

This should be under <system.web>

You could also use culture="auto", in which case the culture will be selected based on the users browser culture settings.

When doing this, and using the [DataType] attribute, then you don't even need to use the [DisplayFormat] attribute.

You might also consider using HtmlAttributeProvider for adding the jq-date attribute to your date types, then no editor template is required at all for your needs. See:

http://blogs.msdn.com/b/ukadc/archive/2012/05/24/asp-net-mvc-adding-html-attributes-in-templated-helpers-editorfor.aspx

If your problem is strictly on the client-side with the jquery date control, then make sure you are initializing it in a jquery ready handler (and you don't need the form id, or the find, just use the class in the jquery selector itself).

$(function() {
    $(".jq-date").datepicker({ dateFormat: 'dd/mm/yy' });
});
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • Really complete answer thanks. I added the culture info but doesn't work better. What is really weird is that it does work on my laptop, but not in my desktop both of them are display date in dd/MM/yyyy, my laptop accepts 25/08/2013 but not my desktop... what the hell? – Tom Aug 05 '13 at 19:19
  • @Tom - are you running it in IIS? IIS Express? The development server? What version of jQuery? What is the exact error? – Erik Funkenbusch Aug 05 '13 at 20:45
  • I'm developping on a IIS express, Jquery 1.8. Exact error: 'The field LoanDate must be a date'. When I put a bad date on my laptop i get another message 'the date 06/29/2013 is not a valid date' – Tom Aug 06 '13 at 06:35
  • Ok like springbokkie suggested, i just saw chrome was giving me the error and not firefox... that's strange – Tom Aug 06 '13 at 15:49
1

It is probably problem with datepicker format. You can set it durring initialization like this

 var dateTypeVar = $('#datepicker').datepicker('getDate');
 $.datepicker.formatDate('dd-mm-yy', dateTypeVar);

You can also set default datetime format. Here are links with more information

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • Thanks for your answer, I will try tomorrow but I do have the init in jquery date picker $("#loanForm").find(".jq-date").datepicker({ dateFormat: 'dd/mm/yy' });. I don't think it works better if i remove the date picker, the control are still validated as MM/dd/yyyy while i want dd/MM/yyyy – Tom Aug 04 '13 at 20:22
  • One more thing in one place in your code you have MM/dd/yyyy in the second you got dd/MM/yyyy – Piotr Stapp Aug 05 '13 at 04:07
  • Good point for the second date, I removed date picker and still doesn't work, so it's really the format expected by unobtrusive validation that doesn't work. – Tom Aug 05 '13 at 19:24
  • 1
    @Tom - MVC doesn't have unobtrusive validation for dates. Dates get posted to the server and if they fail to parse, an error is generated. – Erik Funkenbusch Aug 05 '13 at 21:10
  • Doesn't seem that way please see stackoverflow.com/a/13528769/1741443 – Tom Aug 06 '13 at 17:53
0

Add this below code to global.asax.cs file

protected void Application_BeginRequest() {

CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString()); info.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy"; System.Threading.Thread.CurrentThread.CurrentCulture = info;

}

and add the below to web.config under <system.web>

<globalization culture="en-US" />

Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45