2010-11-06 59 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文件来代替。