执行自定义属性的客户端validation

我创build了一个自定义validation属性:

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

我怎样才能得到这个工作在客户端也使用jQuery?

以下是如何继续:

首先定义自定义validation属性:

 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> 

从你的问题被问到了一小会儿,但是如果你仍然喜欢元数据,而且你仍然打开简单的select,你可以使用下面的注释来解决你的问题:

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

它适用于服务器和客户端,开箱即用。 有关详细信息,请查看ExpressiveAnnotations库。