Demonstrates localisation (sic!) or localization of validation messages for Blazor forms.
Written as an alternative answer for this StackOverflow question, it demonstrates using FluentValidation to add localization support to validation messages.
Blazor supports a default DataAnnotationsValidator
component, but this means closely binding the messages to the model code, and
is therefore difficult to adapt for localization.
FluentValidation provides an answer since it actually has built-in localization support and the validation logic is separated from the actual model, making it easier to customize. Better still it already has localized messages for built-in components.
I created a very simple Blazor client app with a model class ProductViewModel
, and added the FluentValidation library to it and created
a validation class ProductViewModelValidator
:
public class ProductViewModelValidator : AbstractValidator<ProductViewModel>
{
public ProductViewModelValidator()
{
RuleFor(vm => vm.ProductCode).NotEmpty();
}
In a regular application context FluentValidation will use the current culture - however for demonstration purposes I wanted to select the language - and FluentValidation supports that too:
ValidatorOptions.LanguageManager.Culture = new CultureInfo(language);
I also copied Chris Sainty's validation sample to create the FluentValidationValidator
component that replaces the standard DataAnnotationsValidator
For testing purposes I built a list of languages and let the user select. You select the language and click submit:
Acknowledgements/sources: