【问题标题】:Bootstrap DatePicker format not recogined by ASP.NET MVC validatorASP.NET MVC 验证器无法识别引导程序 DatePicker 格式
【发布时间】:2016-09-23 05:05:38
【问题描述】:

我在我的 ASP.NET MVC 应用程序中使用引导日期选择器。当我尝试发布表单时,我收到错误消息 "The field Start Date must be a date." 我正在使用 "jquery.validate.js" 在客户端进行验证。我的日期选择器格式,我自定义为"dd-MM-yyyy"(例如:2016 年 5 月 12 日)。

此错误仅发生在 IE 中,它在 Chrome 浏览器中运行良好。

通过谷歌搜索,我尝试了不同的方法:

1) 在模型中设置数据注释

[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]

2) 编辑jquery.validate.js 中的date 函数

date: function (value, element) {           
            return value.match("^\d{2}-[a-zA-Z]{3}-\d{4}$");
        },

但似乎没有任何效果。大多数问题都是围绕 JQuery datepicker 进行讨论的,但我的是 bootstrap datepicker。

任何帮助将不胜感激。

【问题讨论】:

  • 我遇到了这个问题。我发现的唯一解决方法是向 dtpicker 传递一个字符串而不是 DateTime 并在模型中格式化字符串 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  • @AnimusMiles-Militis 您的意思是将我的模型对象创建为一个简单的字符串而不是 DateTime 字段?如果是,DisplayFormat 属性是否支持字符串对象?

标签: asp.net-mvc twitter-bootstrap date razor datepicker


【解决方案1】:

有一些修复:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime BirthDate { get; set; }

2。 转到全局 asax 并添加:

protected void Application_BeginRequest(Object sender, EventArgs e)
    {

        CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCulture.DateTimeFormat.ShortDatePattern = "dd/MMM/yyyy";
        newCulture.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCulture;
    }
  1. 最后在你的视图中试试这个

    @Html.TextBoxFor(model => model.BirthDate, "{0:dd/MM/yyyy}", new {@class= "date-picker form-control"})

【讨论】:

  • 它现在对我有用。我更改了 dd/MM/yyyy 等格式,而不是 dd/MMM/yyyy。感谢战利品
猜你喜欢
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多