7

I just want to accept Date in ddMMyyyy format while submiting. But its gives an error like

The field FromDate must be a date.

enter image description here

But, When I put date in MMddyyyy it accepts pkkttrfg roperly.
My Model is

public class CompareModel 
{
    [Required]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime FromDate { get; set; }

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

}

My View Part is

<div class="form-group">
        @Html.LabelFor(model => model.FromDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FromDate)
            @Html.ValidationMessageFor(model => model.FromDate)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.TODate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.TODate)
            @Html.ValidationMessageFor(model => model.TODate)
        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Pratik Bhoir
  • 2,074
  • 7
  • 19
  • 36
  • You can look at using jquery globalize or add a method to the `$.validator` as per [this answer](http://stackoverflow.com/questions/27285458/jquery-ui-datepicker-and-mvc-view-model-type-datetime/27286969#27286969) - note that solution is for the jquery ui datepicker but could be adjusted for a standard textbox (e.g. split the value into its components, construct a new javascript `Date()` object and test its valid) –  Feb 13 '15 at 12:15

3 Answers3

11

The problem is behind the scenes it uses javascript to validate this and you need to overwrite this.

jQuery(function ($) {
    $.validator.addMethod('date',
    function (value, element) {
        if (this.optional(element)) {
            return true;
        }

        var ok = true;
        try {
            $.datepicker.parseDate('dd/mm/yy', value);
        }
        catch (err) {
            ok = false;
        }
        return ok;
    });
});

Which was taken from this answer

Community
  • 1
  • 1
nik0lai
  • 2,585
  • 23
  • 37
4

Just try adding

 <system.web>
    <globalization culture="en-GB"/>
</System.web>

Its work for me with same issue

10K35H 5H4KY4
  • 1,496
  • 5
  • 19
  • 41
1

same kind of question i answer before DatePicker format issue

Try to set the culture in web config that match with date format.

<globalization uiCulture="en" culture="en-AU" />

See this link ASP.NET Date time support for different cultures

http://maheshde.blogspot.com.au/2011/09/aspnet-date-time-support-for-different.html

Community
  • 1
  • 1
Mahesh
  • 2,731
  • 2
  • 32
  • 31