您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。