上一篇文章实现的都是服务器端的验证,ASP.net MVC框架给我们提供了非常好的客户端验证机制。下面来修改一下上面的Attribute定义,使其实现IClientValidatable接口
//验证逻辑就是判断专辑的Title是否包含某一个关键字 public class AlbumTitleValidateAttribute : ValidationAttribute,IClientValidatable { private readonly string _keyword; public AlbumTitleValidateAttribute(string keyword) { if (string.IsNullOrEmpty(keyword)) throw new Exception("invalid usage"); _keyword = keyword; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value.ToString().ToUpper().Contains(_keyword.ToUpper())) { return ValidationResult.Success; } else return new ValidationResult(string.Format("Title does not contain the keyword({0})", _keyword)); } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { ModelClientValidationRule rule = new ModelClientValidationRule { ValidationType = "albumtitlecontains", ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters["inputstring"] = _keyword; yield return rule; } }
前台需要使用这两句话来注册验证方法
$.validator.addMethod("albumtitlecontains", function (value, element, param) { if (value.indexOf(param) < 0) { return false; } else { return true; } }); $.validator.unobtrusive.adapters.addSingleVal("albumtitlecontains", "inputstring");
inputstring代表参数要跟rule.ValidationParameters["inputstring"] = _keyword;的名字一致,并且是要小写
albumtitlecontains验证器的名称要跟ValidationType一致,并且是要小写
在使用这些之前,必须保证
1.添加所有的js引用
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
2.Web.config的客户端验证为打开状态
<appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings>