2016-06-27 162 views
-2

我無法正常工作。我想允許用戶選擇start dateend date,如果start date大於end date我想要顯示一條錯誤消息。我正在使用MVC。這是我在模型上的代碼。MVC開始日期和結束日期驗證

public class ModelClass : IValidatableObject 
{ 
    [Required(ErrorMessage = "ID Number is required")] 
    [Display(Name = "ID Number:")] 
    [RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")] 
    public Int64 ID_Number { get; set; } 
    [Required(ErrorMessage = "The start date is required")] 
    [Display(Name = "Start Date:")] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")] 
    public DateTime Start_Date { get; set; } 
    [Required(ErrorMessage = "The end date is required")] 
    [Display(Name = "End Date:")] 
    [GreaterThan("Start_Date")] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")] 
    public DateTime End_Date { get; set; } 





    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) 
    { 
     if (End_Date < Start_Date) 
     { 
      yield return new ValidationResult("EndDate must be greater than StartDate"); 
     } 
    } 
} 
+1

你可能需要像[這]自定義驗證(http://stackoverflow.com/questions/10887824/greater-than-or-equal -to-today-date-validation-annotation-in-mvc3)。 –

+1

那你有什麼問題? –

回答

0

這是你的模型應該如何看起來像:

public class ModelClass : IValidatableObject 
{ 
    [Required(ErrorMessage = "ID Number is required")] 
    [Display(Name = "ID Number:")] 
    [RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")] 
    public Int64 ID_Number { get; set; } 
    [Required(ErrorMessage = "The start date is required")] 
    [Display(Name = "Start Date:")] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")] 
    public DateTime Start_Date { get; set; } 
    [Required(ErrorMessage = "The end date is required")] 
    [Display(Name = "End Date:")] 
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")] 
    public DateTime End_Date { get; set; } 


    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) 
    { 
     if (End_Date < Start_Date) 
     { 
      yield return new ValidationResult("EndDate must be greater than StartDate"); 
     } 
    } 
} 

按下提交按鈕,我們需要檢查,該模型是有效的用戶之後。

ModelState.IsValid

會去您模式,並將驗證模型,如果樁模型是有效的(讓你在你的模型決定的規則),那麼它是有效的。

這是你的行動應該什麼樣子:

[HttpPost] 
public ActionResult Create(ModelClass modelClass) 
{ 
    if (ModelState.IsValid) 
    { 
     db.modelClass.Add(modelClass); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(modelClass); 
} 
+0

我做到了,當我提交它時,即使結束日期小於開始日期也不確認 –

+0

您是否使用ModelState.IsValid? –

+0

不,我用你發佈的代碼@Offir Pe'er: –

相關問題