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");
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。