2016-03-11 39 views
2

我正在开发一个asp.net mvc 5应用程序,其中我试图设置一个验证格式为dd/MM/yyyy格式,我一直在挣扎了很多找到合适的解决方案,但没有成功,我想它接受:日期格式dd/MM/yyyy在asp.net中不工作mvc 5

24/01/2016

,但它显示的验证消息:

现场JoiningDate必须一个约会。

这里是我试过:

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

而且,我希望它无处不在用户端显示DD/MM/YYYY格式的日期,但是,这是第二部分我的问题,首先,它应该至少允许有效的日期输入。我被困在这一个,任何帮助将深深赞赏,我已经遍及搜索,但我无法达到这一点,在此先感谢:)

+0

尝试使用数据类型:[DataType(DataType.Date)] – crunchy

+1

请创建一个[MCVE](http://stackoverflow.com/help/mcve)。 –

+0

假设你的服务器文化是接受'dd/MM/yyyy'中的日期的文化,那么问题是'jquery.validate',它验证'MM/dd/yyyy'格式的日期。你还没有表明,如果你使用日期选择器,但参考[这个答案](http://stackoverflow.com/questions/27285458/jquery-ui-date-picker-and-mvc-view-model-type-datetime/27286969#27286969 )一些选项 –

回答

3

我得到了答案我使用的自定义ModelBinder的,为了解决这个问题,

首先,我注册的这条线在Application_Start方法在Global.asax中:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder()); 

这里是自定义模型绑定器:

public class MyDateTimeModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var displayFormat = bindingContext.ModelMetadata.DisplayFormatString; 
     var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

     if (!string.IsNullOrEmpty(displayFormat) && value != null) 
     { 
      DateTime date; 
      displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty); 
      // use the format specified in the DisplayFormat attribute to parse the date 
      if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) 
      { 
       return date; 
      } 
      else 
      { 
       bindingContext.ModelState.AddModelError(
        bindingContext.ModelName, 
        string.Format("{0} is an invalid date format", value.AttemptedValue) 
       ); 
      } 
     } 

     return base.BindModel(controllerContext, bindingContext); 
    } 
} 

感谢Darin Dimitrov的answer

5

最简单的方法,我发现这是摆在web.config中的下一个

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

有很多清洁的解决方案我想通了。

客户端验证问题可以在jquery.validate.unobtrusive.min.js不以任何方式接受日期/日期时间格式的发生是因为MVC的bug(即使在MVC 5)的。不幸的是,你必须手动解决它。

我终于工作液:

你必须包括前:

@Scripts.Render("~/Scripts/jquery-3.1.1.js") 
@Scripts.Render("~/Scripts/jquery.validate.min.js") 
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") 
@Scripts.Render("~/Scripts/moment.js") 

可以使用安装moment.js:

Install-Package Moment.js 

然后你终于可以添加修复对于日期格式解析器:

$(function() { 
    $.validator.methods.date = function (value, element) { 
     return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid(); 
    } 
});