views:

311

answers:

2

Hello. I'm using System.ComponontModel.DataAnnotations to validate my model objects. How could I replace messages standard attributes (Required and StringLength) produce without providing ErrorMessage attribute to each of them or sub classing them?

+1  A: 

You can use ErrorMessage property of base class ValidationAttribute for all DataAnnotations validators.

For example:

[Range(0, 100, ErrorMessage = "Value for {0} must be between {1} and {2}")]
public int id;

Maybe it'll help.

Veton
True. But is there a way to replace the default message at once?
Mendy
+2  A: 

Writing new post becouse need formatting more than comments provide.

Look at ValidationAttribute - base class of validation attributes.

If validation error occured, error message will be created by method:

public virtual string FormatErrorMessage(string name)
{
    return string.Format(CultureInfo.CurrentCulture, this.ErrorMessageString, new object[] { name });
}

Next look at ErrorMessageString property:

protected string ErrorMessageString
{
    get
    {
        if (this._resourceModeAccessorIncomplete)
        {
            throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, DataAnnotationsResources.ValidationAttribute_NeedBothResourceTypeAndResourceName, new object[0]));
        }
        return this.ResourceAccessor();
    }
}

Property ResourceAccessor can be setted from:

ValidationAttribute..ctor(Func<String>)
ValidationAttribute.set_ErrorMessage(String) : Void
ValidationAttribute.SetResourceAccessorByPropertyLookup() : Void

First of it is exactly used by dervided classes to format messages, second - the case when we set error message trough ErrorMessage property, and third - when resource strings used. Depending on your situation, you may use ErrorMessageResourceName.

Elsewhere let's look at derived constructors, for our example, Range Attribute:

private RangeAttribute()
    : base((Func<string>) (() => DataAnnotationsResources.RangeAttribute_ValidationError))
{
}

Here RangeAttribute_ValidationError is loaded from resource:

internal static string RangeAttribute_ValidationError
{
    get
    {
        return ResourceManager.GetString("RangeAttribute_ValidationError", resourceCulture);
    }
}

So you can create resource file for different tan default culture and overwrite messages there, like this:

http://www.codeproject.com/KB/aspnet/SatelliteAssemblies.aspx

http://msdn.microsoft.com/en-us/library/aa645513(VS.71).aspx

Veton
Thanks a lot Veton. The last part you've mentioned I have totally missed.
Artem Tikhomirov
I can't understand how should the resource files be named (and where placed) to override ResourceManager from DataAnnotations.dll.
wRAR