您好,登錄后才能下訂單哦!
1,自定義驗(yàn)證類(lèi):
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}字符長(zhǎng)度過(guò)長(zhǎng)") { this.MaxLength = maxlength; } /// <summary> /// 服務(wù)端驗(yàn)證方法 /// </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> /// 實(shí)現(xiàn)IClientValidatable接口??蛻?hù)端驗(yàn)證方法 /// </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("客戶(hù)端" + metadata.GetDisplayName()); rule.ValidationType = "zdmaxlength"; rule.ValidationParameters.Add("maxlength", MaxLength); yield return rule; } #endregion } }
2,使用自定義驗(yàn)證類(lèi):
[ZDMaxLength(3)] public string Name { get; set; }
3,視圖代碼:
①:需要引用兩個(gè)腳本和一個(gè)自定義腳本:
<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:驗(yàn)證器名稱(chēng),需要匹配ValidationType //value:輸入值 //element:輸入元素 //zdmaxlength:驗(yàn)證參數(shù) $.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");
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。