2010-11-06 81 views
1

我創建了檢查是否字符串有規定的最小長度定製jQuery驗證屬性不工作

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
    public sealed class MinimumLengthAttribute : ValidationAttribute 
    { 
     public int MinLength { get; set; } 
     private static string _errorMessage = Messages.MinimumLengthError; 

     public MinimumLengthAttribute(int minLength):base(_errorMessage) 
     { 
      MinLength = minLength; 
     } 

     public override string FormatErrorMessage(string name) 
     { 
      var message = String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, MinLength); 
      return message; 
     } 

     public override bool IsValid(object value) 
     { 
      if (value == null) 
      { 
       return true; 
      } 
      string valueAsString = value as string; 
      return (valueAsString != null && valueAsString.Length >= MinLength); 
     } 
    } 

    public class MinimumLengthValidator : DataAnnotationsModelValidator<MinimumLengthAttribute> 
    { 
     public MinimumLengthValidator(ModelMetadata metadata, ControllerContext context, MinimumLengthAttribute attribute) 
      : base(metadata, context, attribute) 
     { 
     } 

     public override IEnumerable<ModelClientValidationRule>GetClientValidationRules() 
     { 
      var rule = new ModelClientValidationRule 
      { 
       ErrorMessage = Attribute.ErrorMessage, 
       ValidationType = "checkMinimumLength" 
      }; 
      rule.ValidationParameters.Add("minimumLength", Attribute.MinLength); 

      return new[] { rule }; 
     } 
    } 

下面定義驗證屬性是我的模型類

public class SignUpViewModel 
    { 
     [Required] 
     [StringLength(100)] 
     public string Username { get; set; } 

     [Required] 
     [MinimumLength(6)] 
     public string Password { get; set; } 
    } 

我有一個js文件,其中包含的客戶端驗證邏輯如下:

jQuery.validator.addMethod("checkMinimumLength", function (value, element, params) { 
    if (this.optional(element)) { 
     return true; 
    } 

    if (value > params.minimumLength) { 
     return true; 
    } 

    return false; 
}); 

我有還註冊我的自定義屬性在我的global.asax文件,但由於某種原因,當我標籤出文本框我得到' $ .validator.methods [...]'爲空或不是對象錯誤在jquery.validate .js文件。我在這裏做錯了什麼?

回答

0

,如果您使用的是包裝版本(jquery.validate.pack.js)。使用的精縮版(jquery.validate.min.js)JavaScript文件來代替。