MVC验证以ddMMyyyy格式接受DateTime [英] MVC Validation to accept DateTime in ddMMyyyy format

查看:66
本文介绍了MVC验证以ddMMyyyy格式接受DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在提交时以ddMMyyyy格式接受Date.但是它给出了类似的错误

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

FromDate字段必须为日期.

The field FromDate must be a date.

但是,当我在MMddyyyy中放置日期时,它会接受pkkttrfg.
我的模特是

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; }

}

我的查看部分是

<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>

推荐答案

问题出在幕后,它使用javascript对此进行了验证,您需要覆盖它.

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;
    });
});

其中哪个来自此答案

这篇关于MVC验证以ddMMyyyy格式接受DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆