question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Localize standard DataAnnotations in ASP.NET Core MVC

See original GitHub issue

The problem

As far as I see from the docs, DataAnnotation localization asks additional resx files, or hardcoded translation strings in [Attributes], or specific code customization, that seem not really fair versus non-English projects.

In order to make "The XX field is required" string to appear as "Le champ XX est obligatoire" we need to write it hardcoded on all decorated with [Required] properties, or write custom code to implement it on all the [Required] properties, and also for all other DataAnnotation attributes, that seem strange…

DataAnnotation should be translated in a similar way another localized strings are, depend on the current culture, be available in localized .json or res files or similar, without the need for each developer to translate by itself the same “Is required” string with same text in their projects.

Further technical details

  • ASP.NET Core version: 5.0.202
  • VS 2019

Linked to

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:42
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

9reactions
ianbriancommented, Sep 18, 2021

Localization should be baked in. I’ve been spending ages replacing hard-coded strings in Identity razor pages. Millions of developers must have done that. What a waste of time.

4reactions
LazZiyacommented, Nov 18, 2022

Many developers prefers official solutions, but sometimes when the wait is too long, you will start developing it yourself or find a community solution.

I’ve developed a nuget (XLocalizer) for simplifing localization in all aspects including auto adding missing keys and online translation support.

In terms of validation there are three main categories:

  • DataAnnotations errors
  • Model binding errors
  • Identity describer errors

Basically there is no need to provide any error message manually, XLocalizer will take care of localizing all automatically. But if you want to customize any error message you can do it simply in startup or json.

  • Option A : In startup

services.AddRazorPages()
        .AddXLocalizer<...>(ops =>
        {
            // Data annotation error messages
            ops.ValidationErrors = new ValidationErrors 
            {
                RequiredAttribute_ValidationError = "The {0} field is required.",
                CompareAttribute_MustMatch = "'{0}' and '{1}' do not match.",
                StringLengthAttribute_ValidationError = "The field {0} must be a string with a maximum length of {1}.",
                // ...
            };

            // Model binding error messages
            ops.ModelBindingErrors = new ModelBindingErrors
            {
                AttemptedValueIsInvalidAccessor = "The value '{0}' is not valid for {1}.",
                MissingBindRequiredValueAccessor = "A value for the '{0}' parameter or property was not provided.",
               // ...
            };

            // Identity Errors
            ops.IdentityErrors = new IdentityErrors
            {
                DuplicateEmail = "Email '{0}' is already taken.",
                DuplicateUserName = "User name '{0}' is already taken.",
                // ...
            }
        });
  • Option B - Json:

{
  "XLocalizerOptions": {

    ....

    "ValidationErrors": {
      "CompareAttribute_MustMatch": "'{0}' and '{1}' do not match. They should not be different!",
      "CreditCardAttribute_Invalid": "The {0} field is not a valid credit card number.",
      "CustomValidationAttribute_ValidationError": "{0} is not valid.",
      ...
    },
    "IdentityErrors": {
      "DuplicateEmail": "Email '{0}' is already taken.",
      "DuplicateUserName": "User name '{0}' is already taken. Please try another one.",
      "InvalidEmail": "Email '{0}' is invalid.",
      ...
    },
    "ModelBindingErrors": {
      "AttemptedValueIsInvalidAccessor": "The value '{0}' is not valid for {1}.",
      "MissingBindRequiredValueAccessor": "A value for the '{0}' parameter or property was not provided.",
      ...
    }
  }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Globalization and localization in ASP.NET Core
Learn how ASP.NET Core provides services and middleware for localizing content into different languages and cultures.
Read more >
c# - Localise Display DataAnnotation without the Name ...
The best and standard solution is to using localization in ASP.NET Core application. In summary, the steps to localize your application are ...
Read more >
Localizing Data Annotation Attributes in ASP.NET Core
Learn how to Localize the models properties using Database with a custom DisplayNameAttribute data annotation in ASP.NET Core.
Read more >
Real World Localization Implementation ASP.NET Core 5
We are primarily concerned with the following features. Localization of DataAnnotations & Validations in View Models; Localization of static ...
Read more >
Localising Data Annotation Attributes in Razor Pages
This is the third article in a series that explores various aspects of localisation in ASP.NET Core Razor Pages applications.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found