DataAnnotations.ValidationAttribute 提供以下幾種
StringLength, Required, RegularExpression, Range 和 DataType 當在 View 裡啟用 ClientValidation (Html.EnableClientValidation) 時,可以看見輸出的 js 裡只包含以上幾種 ValidationType ,自訂的 ValidateionAttribute 在輸出的JS裡沒有對應的 ValidationType 這需要我們自己添加,具體可參考:http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx 下面來實現一下: 1, 定義ValidationAttribute, 原生的 ValidationAttribute 提供了一個 StringLength ,但是只能限定最大長度,這裡我添加最小長度和是否 trimpublic sealed class StringLengthRangeAttribute : ValidationAttribute { public int Max {get; private set;} public int Min {get; private set;} public bool Trim {get; private set;} public StringLengthRangeAttribute( int min, int max ) : base() { Max = Math.Max(min, max); Min = Math.Min(min, max); } public StringLengthRangeAttribute(int min, int max, bool trim) : base( ) { Max = Math.Max(min , max); Min = Math.Min(min , max); Trim = trim; } public override bool IsValid(object value) { if (value == null) return false; string v = Trim ? ((string)value).Trim() : (string)value; if( v.Length < Min || v.Length > Max ) { return false; } else return true; } public override string FormatErrorMessage(string name) { return ErrorMessage; }} 2, 定義 DataAnnotationsModelValidator public class StringLengthRangeValidator : DataAnnotationsModelValidator<StringLengthRangeAttribute> { private int max, min; private bool trim; private string errMsg; public StringLengthRangeValidator(ModelMetadata metaData, ControllerContext ctx, StringLengthRangeAttribute att) : base(metaData, ctx, att) { max = att.Max; min = att.Min; trim = att.Trim; errMsg = att.ErrorMessage; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { ModelClientValidationRule rule = new ModelClientValidationRule { ErrorMessage = errMsg, ValidationType = "StringLengthRange" }; rule.ValidationParameters.Add("min", min); rule.ValidationParameters.Add("max", max); rule.ValidationParameters.Add("trim", trim); return new[] { rule }; } } 這個時候, HTML 裡輸出的 js 裡就會多出類似:{"ErrorMessage":"Password length must between 6 and 16." , "ValidationParameters":{"min":6,"max":16,"trim":false} , "ValidationType":"StringLengthRange"} 3, 註冊, 修改 Global.asax.cs 檔案, 在 Application_Start 裡加上:DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthRangeAttribute), typeof(StringLengthRangeValidator)); 4, 寫個 js 檔案,包含以下內容,並將這個 js 檔案引用 if(String.trim != null) String.prototype.trim = function() {return this.replace(/(^\s*)|(\s*$)/g, "");} Sys.Mvc.ValidatorRegistry.validators["StringLengthRange"] = function(rule) { var min = rule.ValidationParameters["min"]; var max = rule.ValidationParameters["max"]; var trim = rule.ValidationParameters["trim"]; return function(value, context) { if (trim) value = value.trim(); var len = value.length; if (len < min || len > max) return rule.ErrorMessage; else return true; }} OK,就是這麼一個流程。