Data annotation localization in Blazor server-side and WebAssembly (client-side) apps is achieved by referencing the Resource class localized string. Follow these steps to achieve this:
- Add the required localized error messages to the Resource file in the Resource folder.
- In the validation attribute, set the ErrorMessageResourceType as typeof(Resource).
- Assign the required validation message to the ErrorMessageResourceName property.
[Index.razor]
@page "/"
@using {{ApplicationName}}.Resource
@using System.ComponentModel.DataAnnotations;
<EditForm Model="@_employee" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="name" @bind-Value="_employee.Name" />
<button type="submit">Submit</button>
</EditForm>
@code {
public class Employee
{
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(Resource))]
[StringLength(5, ErrorMessageResourceName = "LengthError", ErrorMessageResourceType = typeof(Resource))]
public string Name { get; set; }
}
private Employee _employee = new Employee();
private void HandleValidSubmit()
{
Console.WriteLine("OnValidSubmit");
}
}
Share with