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");