实现StringLengthAttribute类不起作用

时间:2014-02-21 08:35:57

标签: asp.net-mvc data-annotations

我正在尝试实施StringLengthAttribute类以覆盖FormatErrorMessage()方法。

但是,在向属性添加新的StringLengthWithCustomErrorMessage注释后,html输出中缺少不引人注意的验证:

data-val-length="Error message"

我遗失了什么?

public class StringLengthWithCustomErrorMessageAttribute : StringLengthAttribute
{
    public StringLengthWithCustomErrorMessageAttribute(int maximumLength)
        :base(maximumLength)
    {
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format("Value must be between {0} and {1} characters", MinimumLength, MaximumLength);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要为自定义属性添加适配器StringLengthWithCustomErrorMessageAttribute

protected void Application_Start() {
  DataAnnotationsModelValidatorProvider
    .RegisterAdapter(typeof(StringLengthWithCustomErrorMessageAttribute), 
    typeof(StringLengthAttributeAdapter));
}