Error Exceeding Maximum Length in MVC

I am trying to override the maximum length error message in ASP.net MVC. Basically, I would like to make an error message line as follows:

Length

[DisplayName] must not be larger than [x]. However, I do not know how to include the value of the displayname attribute inside.

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "What should I input here"
    }
}
+4
source share
2 answers

If you use StringLengthAttribute {0}, refers to the display name, and {2}refers to the length.

public class MyMaxLengthAttribute : StringLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "{0} length should not be more than {2}"
    }
}
+4
source

Hi, I do not have access to a computer here, but I believe that you need to do something in accordance with.

public class MyMaxLengthAttribute : MaxLengthAttribute
{
     private static String CustomErrorMessage = "{0} length should not be more than {1}";
     public MyMaxLengthAttribute(int length) : base(length)
     {
         ErrorMessage = "What should I input here"
     }

     public override string FormatErrorMessage(string name)
     {
        if (!String.IsNullOrEmpty(ErrorMessage))
        {
            ErrorMessage = MyErrorMessage;
        }
        return String.Format(CultureInfo.CurrentUICulture, CustomErrorMessage , name);
     }
}
+1

Source: https://habr.com/ru/post/1613504/


All Articles