In the handleSubmit-function of a Blazor CRUD component, I have to provide an error message that is based on the DataAnnotation MaxLength-attribute
. I would like to show a "custom" C# error message such as below where "??" is coming from the MaxLength-attribute:
$"The 'Vehicle Number' is limited to {??} characters."
The DataAnnotation in the CRUD-model is:
[Display(Name = "Vehicle Number")]
[MaxLength(12, ErrorMessage = "'{0}' is limited to {1} characters.")]
public string? TXT_VHCL_NUMBER { get; set; }
I know that the namespace is System.ComponentModel.DataAnnotations
should have that value, but I don't know how to get my "Vehicle-Number-field" associated to the specific DataAnnotation MaxLength-attribute.
Values passed to the constructor of an Attribute must be constants (or literals, which are constants).
There's two really easy ways to have your error message show the right number.
First is to just write the number into the string.
[MaxLength(12, ErrorMessage = "'{0}' is limited to 12 characters.")]
Ok, maybe you want to extract the "12" to a variable. Make it a constant then.
class MyData
{
public const int TXT_VHCL_NUMBER_MAX_LENGTH = 12;
[MaxLength(TXT_VHCL_NUMBER_MAX_LENGTH , ErrorMessage = $"'{{0}}' is limited to {TXT_VHCL_NUMBER_MAX_LENGTH} characters.")]
public string? TXT_VHCL_NUMBER { get; set; }
}
Then anywhere else where you want to get that value do MyClass.TXT_VHCL_NUMBER_MAX_LENGTH
.
As I understand your question, using reflection to look up attributes on the property is way overkill. Keep it simple.