MVC3----自定义客户端验证
1,自定义验证类:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace SchoolManageDomw.Models { public class ZDMaxLength : ValidationAttribute,IClientValidatable { private int MaxLength; public ZDMaxLength(int maxlength) : base("{0}字符长度过长") { this.MaxLength = maxlength; } /// <summary> /// 服务端验证方法 /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { if (Convert.ToInt32(value.ToString().Length) > MaxLength) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } } return ValidationResult.Success; } #region IClientValidatable 成员 /// <summary> /// 实现IClientValidatable接口。客户端验证方法 /// </summary> /// <param name="metadata"></param> /// <param name="context"></param> /// <returns></returns> public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule(); rule.ErrorMessage = FormatErrorMessage("客户端" + metadata.GetDisplayName()); rule.ValidationType = "zdmaxlength"; rule.ValidationParameters.Add("maxlength", MaxLength); yield return rule; } #endregion } }
2,使用自定义验证类:
[ZDMaxLength(3)] public string Name { get; set; }
3,视图代码:
①:需要引用两个脚本和一个自定义脚本:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/zd.js")"></script>
②:zd.js
////代码提示 ///<reference path="jquery-1.5.1-vsdoc.js" /> ///<reference path="jquery.validate.js" /> ///<reference path="jquery.validate.unobtrusive.js" /> //zdmaxlength:验证器名称,需要匹配ValidationType //value:输入值 //element:输入元素 //zdmaxlength:验证参数 $.validator.addMethod("zdmaxlength", function (value, element, zdmaxlength) { if (value) { if (value.toString().length > zdmaxlength) { alert(value.toString().length + "." + zdmaxlength); return false; } } return true; }); $.validator.unobtrusive.adapters.addSingleVal("zdmaxlength", "maxlength");
本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1612073
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。