Home > Mobile >  FluentValidation how to return message in several languages
FluentValidation how to return message in several languages

Time:12-26

I have this class :

public class Customer
{
    public string FirstName { get; set; }
    public string Language { get; set; }
}

I'd like to validate the FirstName property. I have to return a message in several languages 'FR', 'EN' like this :

{
    "FR": "Erreur",
    "EN": "Error"
}

with this validator :

public class CustomerValidator : AbstractValidator<Customer>
{
    public CustomerValidator()
    {
        RuleFor(x => x.FirstName)
            .NotEmpty()
            .WithMessage("Error");
    }
}

How can I do this?

Another option could be to return the message depending on the Language property.

CodePudding user response:

you can create a resource file and define the localized strings in it. and based on the language you can get the message in that language.

you can create the resource file by following this link.

Also, refer to this for fluent validation localization.

CodePudding user response:

First, you'll create a resource file for each language you`ll support. You can refer to Microsoft documentation on how to create and work with .resx files.

Then, change your FluentValidator Rule to use your resource file instead of a static string:

RuleFor(x => x.FirstName)
            .NotEmpty()
            .WithMessage(m => MyResouceFile.Error); // Notice the resource file reference

FluentValidator will automatically pick the language based on the Current Culture.

Your consumers will have to specify which language they want it back. There are different options, for example it can be specified in the url: www.example.com/fr/controller/endpoint. Or they can use the HTTP header Accept-Language. Which one to pick is a design decision you'll have to make.

If you opt for the Accept-Language path, you can set the current culture, preferably in a pipeline, like following:

if(Request.UserLanguages != null && Request.UserLanguages.Count > 0)
{
    CultureInfo.CurrentCulture = new CultureInfo(Request.UserLanguages[0], false);
}
else
{
    CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // optionally you may use a sensible default to you, like en-US
}
  • Related