添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Ability to translate all DataAnnotations without having to specify ErrorMessage #4848

Open
@tbolon

Description

@tbolon

Currently, ValidationAttributeAdapterOfTAttribute.GetErrorMessage uses IStringLocalizer only when ErrorMessage is set:

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.

  • You must override the default DataAnnotationLocalizerProvider to return a shared resource.
  • You add a generic entry named, for example, "DataAnnotations_Required" with the translated value format: Le champ {0} doit être renseigné.
  • 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) without having to replace all your data annotations.

    The documentation 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 ?