2014-01-30 45 views
0

我想知道如何設置DateTime屬性的條件需求。也就是說,除了檢查這個必填字段是否爲空,我還希望輸入(在cshtml文件中)不超過3個星期。必填字段 - 條件表達式/驗證

型號:

[DataType(DataType.Date)] 
[Display(Name = "Start date"), Required(ErrorMessage = ValidationMessages.IsRequired)] 
//[What else here for this condition??] 
public DateTime StartDate { get; set; } 

.cshtml:

<div class="form-group"> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.Assignment.StartDate) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.Assignment.StartDate) 
     @Html.ValidationMessageFor(model => model.Assignment.StartDate) 
    </div> 
</div> 

怎麼會這樣的條件表達式是什麼樣子?除了模型中的條件之外,還需要添加一些東西嗎?

請說出我的描述是否太少。

// 在此先感謝,問候

+0

看這個帖子http://stackoverflow.com/questions/1406046/data-annotation-ranges-of-dates – Suni

回答

0

您可以創建自己的驗證屬性象下面這樣:

1)自定義驗證屬性與自定義錯誤消息

public class CheckInputDateAttribute : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var inputDate = (DateTime)value; 
     var compareDate = DateTime.Now.AddDays(21); 
     int result = DateTime.Compare(inputDate, compareDate); 
     const string sErrorMessage = "Input date must be no sooner than 3 weeks from today."; 
     if (result < 0) 
     { 
      return new ValidationResult(sErrorMessage); 
     } 
     return ValidationResult.Success; 
    } 
} 

然後使用它像

[DataType(DataType.Date)] 
    [CheckInputDate] 
    public DateTime StartDate { get; set; } 

2)自定義驗證屬性沒有自定義錯誤消息

public class CheckInputDateAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var inputDate = (DateTime)value; 
     var compareDate = DateTime.Now.AddDays(21); 
     int result = DateTime.Compare(inputDate, compareDate); 
     return result >= 0; 
    } 
} 

然後使用它像

[DataType(DataType.Date)] 
    [Display(Name = "Start date")] 
    [CheckInputDate] 
    public DateTime StartDate { get; set; } 
+0

謝謝,我會試試。 – user3147607

+0

謝謝,這很好。但是,我不覺得有點愚蠢。而不是顯示屬性名稱和消息:「[Assignment.StartDate] =輸入日期必須不超過3周後。」,我想顯示顯示名稱和錯誤消息。 – user3147607

+0

hi @ user3147607,看我更新的答案。 – Lin

0

您可以在模型中做到這一點。添加適當的錯誤消息。

[Required(ErrorMessage = "")] 

[Range(typeof(DateTime), DateTime.Now.ToString(), DateTime.Now.AddDays(21).ToString(), ErrorMessage = "")] 

public DateTime StartDate { get; set; } 
+1

糾正我,如果我錯了,但這不會產生一個編譯錯誤:「屬性參數必須是常量表達式,typeof表達式或屬性參數類型的數組創建表達式」? – LiquidPony

+0

我會試試。直到明天才能嘗試。一個問題,這看起來應該在今天和三週之間,我錯了嗎? – user3147607