senzacionale
senzacionale

Reputation: 20916

C# extend MVC MaxLengthAttribute with own error message

class MyMaxLength : MaxLengthAttribute
    {
        public static String MyErrorMessage = "Maksimalna dolžina za polje {0} je {1}";

        public MyMaxLength(int length)
        {
            new MaxLengthAttribute(length);
        }

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

but I am having a problem with MyMaxLength(int length) constructor. The super class is never called. How can i create my own length validation with predefined message.

Upvotes: 0

Views: 508

Answers (1)

Mike Dinescu
Mike Dinescu

Reputation: 55750

Your syntax is wrong for the constructor.

This is how you invoke the base constructor:

    public MyMaxLength(int length)
            : base(length)           // invoke the base constructor
    {

    }

Something else that might be worth noting is that if you are extending an attribute, while it is not mandatory, it's highly recommended to use the Attribute suffix. In some cases the framework will be looking for type names ending in Attribute.

So, your derived class might be named:

   class MyMaxLengthAttribute : MaxLengthAttribute
   {
        public MyMaxLengthAttribute(int length)
               : base(length)
        {
        }

Upvotes: 2

Related Questions