对自定义属性执行客户端验证

编程入门 行业动态 更新时间:2024-10-11 17:20:07
本文介绍了对自定义属性执行客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个自定义验证属性:

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>

更多推荐

对自定义属性执行客户端验证

本文发布于:2023-10-30 18:20:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   客户端   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!