2012-01-13 17 views
12

我在我的模型中,這datetime屬性:限制與數據註解DateTime值

[Required(ErrorMessage = "Expiration Date is required")] 
[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] 
[DisplayName("Expiration Date")] 
public DateTime? ExpirationDate { get; set; } 

我想驗證這個屬性,使用戶無法進入,今天之前發生的日期。如果我正在驗證一個整數,我可以做到這一點。

[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")] 

但是range屬性不支持DateTime對象。是否有這樣的DateTime值?

+0

可能重複:http://stackoverflow.com/questions/1406046/data-annotation-ranges-of-dates – 2012-01-13 01:24:44

+0

或從本相關的問題的答案也許有:http://stackoverflow.com/問題/ 5390403/datetime-date-and-hour-validation-with-data-annotation – 2012-01-13 01:26:09

+0

我不是100%確定這是與MSDN DateTimeRangeValidator有關,但可能是:http://msdn.microsoft.com/en-us/ library/ff649440.aspx – 2012-01-13 01:29:04

回答

32

這應該對你有所幫助。

public class MyDateAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value)// Return a boolean value: true == IsValid, false != IsValid 
    { 
     DateTime d = Convert.ToDateTime(value); 
     return d >= DateTime.Now; //Dates Greater than or equal to today are valid (true) 

    } 
} 

現在將此屬性應用於您的Model屬性。

public class SomeModel 
    { 
     [Display(Name = "Date of birth")] 
     [MyDate(ErrorMessage ="Invalid date")] 
     public DateTime DateOfBirth { get; set; } 
    } 
+2

您可以使用as [MyDate(ErrorMessage =「您的留言在這裏」)] – Parminder 2017-03-04 23:26:17