2016-03-11 42 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(); 
    } 
});