Feeding DataAnnotations.ValidationAttribute error messages with resource stored string value pairs
-
30-06-2021 - |
Question
My ValidationAttributes
don't access my ErrorMessages
value-pairs stored in a .resx
Resource File generated with VS2010
built in resource generator. (Add New Item - Resources File)
I simply added a folder named Resources
, then added a new Resources File
and called it ErrorResources
, in the resources editor I added a value pair StringLengthError
- Too Long**.
Then in my DataAnnotation.ValidationAttribute I wrote:
[StringLength(5, MinimumLength = 3,
ErrorMessageResourceType = typeof(ErrorResources),
ErrorMessageResourceName = "StringLengthError")]
public string Details { get; set; }
I added a using
statement to include the ErrorResources
.
But when I run it, the ValidationAttribute StringLength is totally void.
If I use it without the ErrorResources, as in :
[StringLength(5, MinimumLength = 3)]
public string Details { get; set; }
The validation attribute comes back to life.
I tried accessing the ErrorResources
value pairs in other part of the code, and it works. I just can't get my ValidationAttributes to use the ErrorResources resource.
La solution
Access modifier should be Public
but that's not enough.
You will have to change properties of your resx file to look like this:
Pay attention to Build Action
and Custom Tool
In addition Resx
used by data annotations should sit in App_GlobalResources
rather than in Resources
you've mentioned. Try these, see if that works alright.
Hope this will help you.
Autres conseils
Try change Access Modifier
setting of Resources File to public
!