Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Validation to accept DateTime in ddMMyyyy format

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>
like image 519
Pratik Bhoir Avatar asked Feb 13 '15 11:02

Pratik Bhoir


2 Answers

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

like image 196
nik0lai Avatar answered Sep 18 '22 10:09

nik0lai


Just try adding

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

Its work for me with same issue

like image 33
10K35H 5H4KY4 Avatar answered Sep 19 '22 10:09

10K35H 5H4KY4