Ability to translate all DataAnnotations without having to specify ErrorMessage
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 276
Description
Currently, [ValidationAttributeAdapterOfTAttribute.GetErrorMessage](https://github.com/aspnet/Mvc/blob/900a5c7c4c789e71bf18e8e90bf9b28b4e51013f/src/Microsoft.AspNetCore.Mvc.DataAnnotations/ValidationAttributeAdapterOfTAttribute.cs#L67) uses IStringLocalizer only when ErrorMessage is set:
```csharp
protected virtual string GetErrorMessage(ModelMetadata modelMetadata, params object[] arguments)
{
if (modelMetadata == null)
{
throw new ArgumentNullException(nameof(modelMetadata));
}
if (_stringLocalizer != null &&
!string.IsNullOrEmpty(Attribute.ErrorMessage) &&
string.IsNullOrEmpty(Attribute.ErrorMessageResourceName) &&
Attribute.ErrorMessageResourceType == null)
{
return _stringLocalizer[Attribute.ErrorMessage, arguments];
}
return Attribute.FormatErrorMessage(modelMetadata.GetDisplayName());
}
```
The consequence is that you have to set the ErrorMessage property each time you want to translate an error message.
Suppose you just want to translate the default RequiredAttribute ErrorMessageString, which is `The {0} field is required.` for all your Model classes.
1) You must override the default DataAnnotationLocalizerProvider to return a shared resource.
2) You add a generic entry named, for example, "DataAnnotations_Required" with the translated value format: `Le champ {0} doit être renseigné.`
3) You must replace all the `[Required]` attributes with `[Required(ErrorMessage = "DataAnnotations_Required")]`
More generally, there is no way to just adapt the generic DataAnnotation validation messages to your language. (the ones in [System.ComponentModel.Annotations.SR.resources](https://github.com/dotnet/corefx/blob/master/src/System.ComponentModel.Annotations/src/Resources/Strings.resx)) without having to replace all your data annotations.
The [documentation](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization#dataannotations-localization) only provide a sample where the messages are customized for each property (despite the fact that only the property name change).
There is no easy workaround either:
- You can't inherit from RequiredAttribute to fix the ErrorMessage property, since the framework uses strict type comparison
- Replacing the default ValidationAttributeAdapterProvider is not trivial, because you have to replace all adapters with custom ones to override the GetErrorMessage method.
Is there a better way to achieve localization for all default data annotation error messages ?
Or room for improvement in asp.net core mvc to reduce the burden of writing all this custom code ?
Contributor guide
Assessment
This issue has not been assessed yet.