MVC3----自定义客户端验证
1,自定义验证类:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.ComponentModel.DataAnnotations;usingSystem.Web.Mvc;namespaceSchoolManageDomw.Models{publicclassZDMaxLength:ValidationAttribute,IClientValidatable{privateintMaxLength;publicZDMaxLength(intmaxlength):base("{0}字符长度过长"){this.MaxLength=maxlength;}///<summary>///服务端验证方法///</summary>///<paramname="value"></param>///<paramname="validationContext"></param>///<returns></returns>protectedoverrideValidationResultIsValid(objectvalue,ValidationContextvalidationContext){if(value!=null){if(Convert.ToInt32(value.ToString().Length)>MaxLength){returnnewValidationResult(FormatErrorMessage(validationContext.DisplayName));}}returnValidationResult.Success;}#regionIClientValidatable成员///<summary>///实现IClientValidatable接口。客户端验证方法///</summary>///<paramname="metadata"></param>///<paramname="context"></param>///<returns></returns>publicIEnumerable<ModelClientValidationRule>GetClientValidationRules(ModelMetadatametadata,ControllerContextcontext){varrule=newModelClientValidationRule();rule.ErrorMessage=FormatErrorMessage("客户端"+metadata.GetDisplayName());rule.ValidationType="zdmaxlength";rule.ValidationParameters.Add("maxlength",MaxLength);yieldreturnrule;}#endregion}}
2,使用自定义验证类:
[ZDMaxLength(3)]publicstringName{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
////代码提示///<referencepath="jquery-1.5.1-vsdoc.js"/>///<referencepath="jquery.validate.js"/>///<referencepath="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);returnfalse;}}returntrue;});$.validator.unobtrusive.adapters.addSingleVal("zdmaxlength","maxlength");
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。