2011-01-20 347 views

回答

161

下面是如何進行的:

開始通過定義自定義驗證屬性:

public class FutureDateAttribute : ValidationAttribute, IClientValidatable 
{ 
    public override bool IsValid(object value) 
    { 
     if (value == null || (DateTime)value < DateTime.Now) 
      return false; 

     return true; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     yield return new ModelClientValidationRule 
     { 
      ErrorMessage = this.ErrorMessage, 
      ValidationType = "futuredate" 
     }; 
    } 
} 

注意它是如何實現IClientValidatable。接下來,我們寫我們的模型:

public class MyViewModel 
{ 
    [FutureDate(ErrorMessage = "Should be in the future")] 
    public DateTime Date { get; set; } 
} 

然後控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new MyViewModel 
     { 
      // intentionally put in the past 
      Date = DateTime.Now.AddDays(-1) 
     }); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     return View(model); 
    } 
} 

最後一個觀點:

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(x => x.Date) 
    @Html.TextBoxFor(x => x.Date) 
    @Html.ValidationMessageFor(x => x.Date) 
    <input type="submit" value="OK" /> 
} 

的神奇發生的最後一部分是定義自定義適配器:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> 
<script type="text/javascript"> 
    // we add a custom jquery validation method 
    jQuery.validator.addMethod('greaterThan', function (value, element, params) { 
     if (!/Invalid|NaN/.test(new Date(value))) { 
      return new Date(value) > new Date($(params).val()); 
     } 
     return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); 
    }, ''); 

    // and an unobtrusive adapter 
    jQuery.validator.unobtrusive.adapters.add('futuredate', { }, function (options) { 
     options.rules['greaterThan'] = true; 
     options.messages['greaterThan'] = options.message; 
    }); 
</script> 
+3

輝煌的答案! – raklos 2011-01-20 13:46:18

+0

幾乎工作 - 日期應該是什麼格式? – raklos 2011-01-20 15:01:56

4

它花了一會兒,因爲你的問題被問,但如果你還是喜歡的元數據,並且你還開着簡化方案,則可以使用以下註解解決您的問題:

[Required] 
[AssertThat("Date > Now()")] 
public DateTime? Date { get; set; } 

它同時適用於 - 服務器和客戶端,盒子外面。欲瞭解更多詳情,請看ExpressiveAnnotations圖書館。