Question

I am having an issue where a date formatted as dd-MMM-yyyy is not being recognized as a date. I get the error "The field Start date must be a date." for a date picked with the datepicker 30-NOV-2013.

Model

  [Required]
  [DataType(DataType.Date)]
  [Display(Name = "Start date")]
  [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
  public DateTime StartDate { get; set; }

View @Html.ValidationSummary()

    @Html.LabelFor(m => m.StartDate)
    @Html.EditorFor(m => m.StartDate) 
    @Html.ValidationMessageFor(m => m.StartDate)
     <div>
        <input type="submit" value="Set on leave" id="setLeave" />
    </div>

    <script type="text/javascript">
    $("#StartDate").datepicker({
            showAnim: 'fadeIn',
            dateFormat: 'dd-M-yy',
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true
        }).prop('readOnly', true);
    </script>
Was it helpful?

Solution

I would suggest to use jQuery Globalize and customize dates validation:

$(document).ready(function () {

    Globalize.culture('en-GB');

    $.validator.methods.date = function (value, element) {
        return (this.optional(element) || Globalize.parseDate(value, 'dd-MMM-yyyy'));
    }

});

You can read something more about jQuery Globalize here.

OTHER TIPS

Just hit this with format dd/mm/yy, but rather than pulling in another dependency (jQuery Globalize) I made use of the jQuery UI's inbuilt date parser as I already had that date picker working on the field:

$.validator.methods.date = function (value, element) {
  return (this.optional(element)
        || $.datepicker.parseDate('dd/mm/yy', value));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top