我创建了一个自定义验证属性,用于检查字符串是否具有指定的最小长度
[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 :(得分:0)
如果您使用打包版本(jquery.validate.pack.js)。请使用缩小版本(jquery.validate.min.js)javascript文件。