I'm working on a ASP .Net Core 5 project, where I created a custom Validation Attribute and in case when the validation result is not valid I want to return a localized error message.
Here is the ViewModel with the validation attribute:
public class MyViewModel()
{
[Required(ErrorMessage = "RequiredMsg")]
[CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
public string Name { get; set; }
[Required(ErrorMessage = "RequiredMsg")]
[CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
public string SureName { get; set; }
[Required(ErrorMessage = "RequiredMsg")]
[CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
public string Address { get; set; }
[Required(ErrorMessage = "RequiredMsg")]
public string Phone { get; set; }
[Required(ErrorMessage = "RequiredMsg")]
[CheckTextIsValid(new char[] { 'a', 'b', 'c' }, ErrorMessage = "NotAllowedChars")]
public string Country { get; set; }
}
The "RequiredMsg" is localized and it works, so when there's error I can see the value of "RequiredMsg" = "This feild is required". But it's not working for "NotAllowedChars".
Here is CheckTextIsValid validation code:
public class CheckTextIsValid :ValidationAttribute
{
private char[] NotAllowedChars { get; set; }
public CheckTextIsValidForSdi(char[] notAllowedChars)
{
NotAllowedChars = notAllowedChars;
}
public override bool IsValid(object value)
{
..... Logic..
if(//IsValid)
{
return ValidationResult.Success;
}else{
return new ValidationResult( string.Format(ErrorMessage, notAllowedChars)); // Here the ErrorMessage is "NotAllowedChars"
}
}
}
How can I read the value of "NotAllowedChars" from the resources?
I know that there's a lot of questions about this: (
ASP.NET Core custom validation attribute localization,
ErrorMessageTranslationService, This is work perfectly with IHtmlLocalizer
. ButI need to IHtmlLocalizer<T>
because I'm gonna use CheckTextIsValid()
in different View Models and pass different error messages.
), but still I couldn't fix this problem.