How to correctly localize validation in the IValidatableObject.Validate method for ASP.Net Core MVC

I have a model that implements IValidatableObject and I need to localize ValidationResults, how can I achieve this correctly?

Currently, I came up with the IValidatableObject.Validate method, which looks like this:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var stringLocalizer = validationContext.GetService(typeof(IStringLocalizer<MyModel>)) as IStringLocalizer<MyModel>; //Validation logic implementation... yield return new ValidationResult(stringLocalizer["This thing is the error message"]); } 

What I'm doing here is finding an instance of IStringLocalizer using the ValidationContext.GetService method.

This approach works, but my main problem is that I'm not quite sure if this is correct, because I need to rely on a service locator to get IStringLocalizer

+5
source share

Source: https://habr.com/ru/post/1263306/


All Articles