How to Localize validation message (DataAnnotationsValidator) in blazor server side
Here is my solution for localizing data annotation error messages. I create two resource files, one for fields and another one for error messages.
DisplayNameResource
for localizing fieldsErrorMessageResource
for localizing error messages
In view model class use Display
attribute for localizing field name. To specify resource file use ResourceType
property on Display
attribute:
[Display(Name = "Address", ResourceType = typeof(DisplayNameResource))]
And on validation attributes use ErrorMessageResourceName
and ErrorMessageResourceType
to specify resource file:
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
Here is full example:
public class SomeViewModel
{
[Display(Name = "Address", ResourceType = typeof(DisplayNameResource))]
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
[StringLength(256, ErrorMessageResourceName = "MaxLengthError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
public string Address { get; set; }
[Display(Name = "Phone", ResourceType = typeof(DisplayNameResource))]
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
[RegularExpression("^09([0-9]{9})$", ErrorMessageResourceName = "PhoneLengthError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
public string Phone { get; set; }
[Display(Name = "Password", ResourceType = typeof(DisplayNameResource))]
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
[StringLength(50, MinimumLength = 6, ErrorMessageResourceType = typeof(ErrorMessageResource), ErrorMessageResourceName = "MinxMaxLengthError")]
public string Password { get; set; }
[Display(Name = "ConfirmPassword", ResourceType = typeof(DisplayNameResource))]
[Required(ErrorMessageResourceName = "RequiredError", ErrorMessageResourceType = typeof(ErrorMessageResource))]
[StringLength(50, MinimumLength = 6, ErrorMessageResourceType = typeof(ErrorMessageResource), ErrorMessageResourceName = "MinxMaxLengthError")]
[Compare("Password", ErrorMessageResourceName = "PasswordConfirmMisMatch", ErrorMessageResourceType = typeof(ErrorMessageResource))]
public string ConfirmPassword { get; set; }
}
Error message for MaxLengthError
is {0} cannot be longer than {1} character
, so {0}
will be replaced with localized filed name and {1}
will be replaced with the 256
you specified on attribute [StringLength(256,...