2013-09-25 157 views
-1

我想要定製驗證日期,其中年齡大於或等於18爲年齡自定義驗證必須大於或等於18

可以在任何一個想法與自定義驗證mvc4?

請讓我知道,如果任何解決方案是有..

問候

+0

我想讓年齡驗證從日期選擇器選擇日期.. 。請讓我知道任何一個已執行自定義驗證.. – user2805091

回答

1

只需使用一個Range驗證:

[Range(18, int.MaxValue)] 
public int Age { get; set; } 

它是System.ComponentModel.DataAnnotations命名空間中可用。

UPDATE

爲了驗證一個日期是年滿18歲前,你可以使用自定義驗證屬性是這樣的:

public class Over18Attribute : ValidationAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     string message = String.Format("The {0} field is invalid.", validationContext.DisplayName ?? validationContext.MemberName); 

     if (value == null) 
      return new ValidationResult(message); 

     DateTime date; 
     try { date = Convert.ToDateTime(value); } 
     catch (InvalidCastException e) { return new ValidationResult(message); } 

     if (DateTime.Today.AddYears(-18) >= date) 
      return ValidationResult.Success; 
     else 
      return new ValidationResult("You must be 18 years or older."); 
    } 
} 
+0

我可以使用它的消息? – user2805091

+0

從datepicker滿足年齡? – user2805091

+0

@ user2805091檢查我的更新。 – asymptoticFault