0

I Add a Resource File to my projects and I write a Service :

using Microsoft.Extensions.Localization;
using System.Reflection;
namespace NzShop.Services
{
    public class ComponentsResourceService
    {

        private readonly IStringLocalizer localizer;
        public ComponentsResourceService(IStringLocalizerFactory factory)
        {
            var assemblyName = new AssemblyName(typeof(ComponentsResource).GetTypeInfo().Assembly.FullName!);
            localizer = factory.Create(nameof(ComponentsResource), assemblyName.Name!);
        }

        public string Get(string key)
        {
            return localizer[key];
        }
        public class ComponentsResource { }
    }
}

In Program.cs add:

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
     {
        new CultureInfo("en"),
        new CultureInfo("fa"),
        new CultureInfo("tr"),
        new CultureInfo("en-US")
    };
    options.DefaultRequestCulture = new RequestCulture("en");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

builder.Services.AddMvc().AddViewLocalization()
                    .AddDataAnnotationsLocalization();

builder.Services.AddSingleton<ComponentsResourceService>();

How Can control Required Field from my ComponentsResource.resx file:

[Required(ErrorMessage = ?????)]
public string Familly { get; set; }
Dave B
  • 1,105
  • 11
  • 17
Farna
  • 1,157
  • 6
  • 26
  • 45

2 Answers2

0

You can directly bind the resource to ErrorMessage.

[Required(ErrorMessage = "{ComponentsResource.FamilyRequired}")]
public string Family { get; set; }
AVTUNEY
  • 923
  • 6
  • 11
0

There are multiple ways to set a localized error message for the Required attribute using the .resx file and there are many Stack Overflow and blog posts that cover this topic.

[Required(ErrorMessage = ?????)]

ErrorMessageResourceName/Type validation attributes

A simple, reliable solution that leverages IntelliSense features/validation is to use the combination of the ErrorMessageResourceName and ErrorMessageResourceType validation attributes along with nameof and typeof.

[Required(ErrorMessageResourceName = nameof(ComponentsResource.Required),
    ErrorMessageResourceType = typeof(ComponentsResource))]
  • ComponentsResource "is the class corresponding to the .resx file where the validation messages are stored".
  • The nameof expression provides IntelliSense completion for resources defined in the .resx file.
  • The typeof operator provides validation of the existence of the ComponentsResource class.

Applying the above to your property:

[BindProperty]
[Required(ErrorMessageResourceName = nameof(ComponentsResource.Required),
    ErrorMessageResourceType = typeof(ComponentsResource))]
public string? Familly { get; set; }

enter image description here

These attributes are used in these SO posts here and here but answers does not leverage nameof while this blog post does. These posts suggest, however, a common data annotation localization provider configured through the program.cs file versus the ErrorMessageResourceName/ErrorMessageResourceType validation attributes above.

IValidationMetadataProvider

This Stack Overflow post provides a solution where a localized string format for a validation attribute like [Required] is configured commonly through program.cs.

builder.Services
    .AddMvc(options =>
    {
        options.ModelMetadataDetailsProviders.Add(new LocalizedValidationMetadataProvider());
    })
    .AddDataAnnotationsLocalization();

where the validation metadata provider is defined as:

public class LocalizedValidationMetadataProvider : IValidationMetadataProvider
{
    public LocalizedValidationMetadataProvider()
    {
    }

    public void CreateValidationMetadata(ValidationMetadataProviderContext context)
    {
       ....
    }
}

The SO post provides the full set of steps and code.

Dave B
  • 1,105
  • 11
  • 17