自定义属性上执行客户端验证 [英] Perform client side validation for custom attribute
本文介绍了自定义属性上执行客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个自定义验证属性:
I have created a Custom Validation Attribute:
public class FutureDateAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null|| (DateTime)value < DateTime.Now)
return false;
return true;
}
}
我怎样才能得到这个在客户端工作太与jQuery?
How can I get this to work on client side too with jquery?
推荐答案
下面是如何进行:
通过定义自定义验证属性启动:
Start by defining the custom validation attribute:
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.接下来我们写我们的模型:
Notice how it implements IClientValidatable. Next we write our model:
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" />
}
有关魔术发生的最后一部分是定义自定义适配器:
The last part for the magic to happen is to define the custom adapter:
<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>
这篇关于自定义属性上执行客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文