Default resource for data annotations in ASP.NET MVC

Kim Tranjan picture Kim Tranjan · Jul 16, 2010 · Viewed 7.4k times · Source

There's a way to set the default resource to the data annotations validations?

I don't wanna make something like this:

[Required(ErrorMessage="Name required.", ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }

I would like something like this:

Global.asax

DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources);

then

[Required]
public string Name { get; set; }

someone gimme a light!

thanks in advance

EDIT

My real problem was with EF Code First CTP4. CTP5 fix it. Thanks for everyone.

Answer

CGK picture CGK · Dec 3, 2010

You could try doing this:

Add this class somewhere in your project:

 public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator<ValidationAttribute>
{
    /// <summary>
    /// The type of the resource which holds the error messqages
    /// </summary>
    public static Type ResourceType { get; set; }

    /// <summary>
    /// Function to get the ErrorMessageResourceName from the Attribute
    /// </summary>
    public static Func<ValidationAttribute, string> ResourceNameFunc 
    {
        get { return _resourceNameFunc; }
        set { _resourceNameFunc = value; }
    }
    private static Func<ValidationAttribute, string> _resourceNameFunc = attr => attr.GetType().Name;

    public ExternalResourceDataAnnotationsValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)
        : base(metadata, context, attribute)
    {
        if (Attribute.ErrorMessageResourceType == null)
        {
            this.Attribute.ErrorMessageResourceType = ResourceType;
        }

        if (Attribute.ErrorMessageResourceName == null)
        {
            this.Attribute.ErrorMessageResourceName = ResourceNameFunc(this.Attribute);
        }
    }
}

and in your global.asax, add the following:

// Add once
ExternalResourceDataAnnotationsValidator.ResourceType = typeof(CustomDataAnnotationsResources);

// Add one line for every attribute you want their ErrorMessageResourceType replaced.
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(ExternalResourceDataAnnotationsValidator));

It will look for a property with the same name as the validator type for the error message. You can change that via the ResourceNameFunc property.

EDIT: AFAIK this works from MVC2 onwards, as DataAnnotationsModelValidatorProvider was introduced in MVC2.