MVC Validation to accept DateTime in ddMMyyyy format

☆樱花仙子☆ 提交于 2021-02-04 17:52:06

问题


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>

回答1:


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




回答2:


Just try adding

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

Its work for me with same issue




回答3:


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



来源:https://stackoverflow.com/questions/28499095/mvc-validation-to-accept-datetime-in-ddmmyyyy-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!