views:

21

answers:

1

I am using data annotations to validate an emailaddress.

To show an error message when the emailaddress is not valid, I use a RESX file called ErrorMessages.

My code is like this:

public class EmailAdressAttribute : RegularExpressionAttribute
{
    public EmailAdressAttribute()
        : base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,3}|[0-9]{1,4})(\]?)$")
    {

        ErrorMessage = ErrorMessages.ValidateEmailAdress;
    }

When I change to language (current culture) of my asp.net mvc application while running the application, the old language is still shown.
After debugging I found out that the constructor for this attribute is only called once(when I use it for the first time ).

How is the attribute being cached ? How can I show the correct error message from the resource file?

+2  A: 

Instead of setting the value of your ErrorMessage property in the constructor, how about overriding that property and reading that text from the resource at the moment it's needed?

public override string ErrorMessage
{
   get { return ErrorMessages.ValidateEmailAdress; }
}

The attribute is not something that belongs to an instance of the class, but to the Type. That's why it is constructed only once in your app's lifetime.

Hans Kesting
Thanks, the solution worked (without using the override keyword).
Jan
Good! I guessed that ErrorMessage was a property of the baseclass. Apparently it belongs to the EmailAddressAttribute class.
Hans Kesting