I created a Custom Validation Attribute that only validates if a CPF property is a valid CPF, but when I Localize the application I noticed that my Custom Attribute was not having its messages localized by the Framework, unlike the Data Attribute Required
that has its message located correctly:
Example of using attributes with Required being correctly localized.
[Required(ErrorMessage = "CPF Requerido")]
[CPF(ErrorMessage = "CPF Inválido")]
public string CPF { get; set; }
Setting the location in the Startup.cs file
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
return factory.Create(typeof(SharedResource));
};
});
Custom validation class:
public class CPFAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
//Omitted for not being part of the context
}
}
Versions:
Microsoft.AspNetCore.App (2.1.1)
Microsoft.NETCore.App (2.1)