2010-09-02 91 views
3

我有一個數據驗證類,用於檢查會議的開始日期是否在結束日期之前。將數據從模型傳遞到自定義驗證類

該模型自動通過需要驗證的日期,但我有點難以傳遞需要驗證的數據。

這裏是我的驗證類

sealed public class StartLessThanEndAttribute : ValidationAttribute 
    {    
     public DateTime DateEnd { get; set; } 

     public override bool IsValid(object value) 
     {     
      DateTime end = DateEnd; 
      DateTime date = (DateTime)value; 

      return (date < end); 
     } 

     public override string FormatErrorMessage(string name) 
     { 
      return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name); 
     } 
    } 

這裏是一個包含數據的註釋

[StartLessThanEnd(ErrorMessage="Start Date must be before the end Date")] 
public DateTime DateStart { get; set; } 

這是我的控制器

[HttpPost, Authorize] 
    public ActionResult Create(Pol_Event pol_Event) 
    { 
     ViewData["EventTypes"] = et.GetAllEventTypes().ToList(); 

     StartLessThanEndAttribute startDateLessThanEnd = new StartLessThanEndAttribute(); 


     startDateLessThanEnd.DateEnd = pol_Event.DateEnd; 


     if (TryUpdateModel(pol_Event)) 
     { 
      pol_Event.Created_On = DateTime.Now; 
      pol_Event.Created_By = User.Identity.Name; 

      eventRepo.Add(pol_Event); 
      eventRepo.Save(); 
      return RedirectToAction("Details", "Events", new { id = pol_Event.EventID }); 
     } 

     return View(pol_Event); 
    } 

回答

3

驗證屬性是具有多個屬性的工作應該是類適用於模型而不是單個屬性:

[AttributeUsage(AttributeTargets.Class)] 
public class StartLessThanEndAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     var model = (MyModel)value; 
     return model.StartDate < model.EndDate; 
    } 
} 

[StartLessThanEnd(ErrorMessage = "Start Date must be before the end Date")] 
public class MyModel 
{ 
    public DateTime StartDate { get; set; } 
    public DateTime EndDate { get; set; } 
} 
+0

偉大的現在我怎麼做在客戶端驗證的GetClientValidationRules方法。我想將一些屬性值傳遞給客戶端驗證規則。 – War 2013-03-19 16:43:55

+0

如何捕捉驗證邏輯模型的好例子,謝謝。 – 2013-07-16 00:36:33