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" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="@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");
共同学习,写下你的评论
评论加载中...
作者其他优质文章