如何使用新的错误消息创建自定义MaxLength和Required验证,逻辑保持不变

sen*_*ale 3 c# asp.net-mvc-3

[MaxLength(45, ErrorMessage = Translations.Attribute.MAX_LENGTH)]
[Required(ErrorMessage = Translations.Attribute.REQUIRED)]
Run Code Online (Sandbox Code Playgroud)

如何使用默认的已翻译消息创建自定义RequiredMaxLength验证。我可以简单地覆盖它并仅更改errorMessage吗?

我只想写

[MyMaxLength(45)]
[MyRequired]
Run Code Online (Sandbox Code Playgroud)

已建立所需解决方案:

public class MyRequiredAttribute : RequiredAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return string.Format("Polje {0} je obvezno", name);
        }
    }
Run Code Online (Sandbox Code Playgroud)

dav*_*v_i 5

您应该能够从MaxLengthAttribute或任何其他正在使用的属性中得出...

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = Translations.Attribute.MAX_LENGTH;
    }

    // other ctors/members as needed
}
Run Code Online (Sandbox Code Playgroud)

  • 这将负责服务器端验证,但您将没有任何客户端jquery验证。如果您使用的是MVC,则还需要创建MyMaxValidator (2认同)