【问题标题】:Finally solved: The field must be a date终于解决了:字段必须是日期
【发布时间】:2020-09-26 04:08:29
【问题描述】:

问题:

我需要捕获日期和时间数据,我在我的模型类上写了这个:

[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]

public DateTime DateofBirth{ get; set; }

我有这个日期选择器设置:

$('#DateofBirth').datepicker({
                dateFormat: "dd MM yy",
                changeMonth: true,
                changeYear: true,
                autoclose: true,
            });

当我选择一个日期时,文本框验证总是说:“出生日期字段必须是一个日期”。 即使我不使用 datepicker(我手动编写日期),它也会这样说。

当我从提供的许多解决方案中阅读时,我认为这与 javascript 或 jquery 有关。但是,验证一直说“出生日期字段必须是日期”。

经过一番搜索,没有好的结果,我终于意识到ASP.NET使用的日期时间格式与jQuery使用的日期时间格式不同。 正如this link 所说,日期和时间的一般 DataFormatString 是 2009 年 6 月 15 日下午 1:45:30,所以如果我不完全按照那种格式写,验证错误就会弹出。甚至,当我使用 datepicker 填充文本框时。

【问题讨论】:

  • 如果您想发布解决方案,请将其放在答案中,而不是在您的问题中
  • 好的,谢谢你的建议。

标签: c# jquery date validation datepicker


【解决方案1】:

解决方案:

基于this linkthis link,我必须匹配 ASP.NET 模型和 jQuery 日期选择器的日期时间。

因此,我在模型类中将自定义日期时间格式编写为 dd MMMM yyyy

[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:dd MMMM yyyy}")]

public DateTime DateofBirth{ get; set; }

在 jQuery datepicker 属性中日期时间格式为 dd MM yy,像这样

$('#DateofBirth').datepicker({
                dateFormat: "dd MM yy",
                changeMonth: true,
                changeYear: true,
                autoclose: true,
            });

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多