There\'s a way to set the default resource to the data annotations validations?
I don\'t wanna make something like this:
[Required(ErrorMessage=\"Nam
You could try doing this:
Add this class somewhere in your project:
public class ExternalResourceDataAnnotationsValidator : DataAnnotationsModelValidator
{
///
/// The type of the resource which holds the error messqages
///
public static Type ResourceType { get; set; }
///
/// Function to get the ErrorMessageResourceName from the Attribute
///
public static Func ResourceNameFunc
{
get { return _resourceNameFunc; }
set { _resourceNameFunc = value; }
}
private static Func _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.