简体   繁体   中英

Localize DataAnnotations in Asp.net core

In my asp.net core (.net5) application I have a form with a required field. When the field is empty I have

在此处输入图像描述

"The XX field is required"... In English... I want to translate it in French. I mean, I don't really want to translate , I want to use the French version of the message. I don't want to add Resource files, because I have any custom strings to translate, I just want to use existing messages, but in French.

I started to read here but did't really get the point if the article really proposes me to translate each message manually by myself.

I added this one in the Configure

var supportedCultures = new[] { "fr-FR" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures);

app.UseRequestLocalization(localizationOptions);

however this didn't change the message...

nor setting the culture params via URL, like this

在此处输入图像描述

If you just want one french version, you just need to define the error message in [Required]

attribute, like:

public class MyModel
{
    [Required(ErrorMessage = "Le champ Nom est obligatoire")]
    public string Nom { get; set; }
}

And if your shared code refers to the documention you shared, you need to add Resource file to

define the translated message, or the message will not changed.

Edit:

If you have other properties, you can define a customRequired attribute:

 public class CustomRequiredAttribute : ValidationAttribute
{
    public CustomRequiredAttribute()
    {         
    }
    
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            ErrorMessage = $"Le champ {validationContext.DisplayName} est obligatoire";
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

Model:

public class MyModel
{   
    [CustomRequired]  //custom attribute
    public string Nom { get; set; }        
    [CustomRequired]
    public string PreNom { get; set; }
}

To use your custom attribute, you should add ModelState.IsValid in your post action, so if invalid, it will return the input view to show the errorMessages,like:

[HttpPost]
    public IActionResult Privacy(MyModel myModel)
    {
        if (!ModelState.IsValid)
            return View("Index");
        return View();
    }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM