0

I have this extension method in order to retrieve the validation error message of a property:

public static string GetValiAttriError(this object instance, string propertyName)
{
    var attrType = typeof(ValidationAttribute);
    var property = instance.GetType().GetProperty(propertyName);
    var r = (ValidationAttribute)property.GetCustomAttributes(attrType, false).First();
    return r.ErrorMessage;
}

and this is how I call it:

UserForReg userForRegi = new UserForReg();
var errorMessage = userForReg.GetValiAttriError("PropertyName");

Instead of having to use a magic string like in this case "PropertyName" for the name of the property I could love to have a typed solution to avoid error during execution when the name of a property changes.

Something linke this would be wonderful (without even the need of an instance of UserForReg):

var errorMessage = GetValiAttriError(UserForReg.PropertyName);

Is it possible?

Fabianus
  • 633
  • 7
  • 16
  • 5
    Maybe `nameof(UserForReg.PropertyName)`? – dymanoid Feb 18 '20 at 08:50
  • yes it does ! Thanks a lot dymanoid. And is there a way to avoid passing by the string at all? I mean could my extension methode become a methode with a parameter that receives UserForReg.PropertyName directly and uses this to retrieve the validationAttribute's error message? To make things shorter – Fabianus Feb 18 '20 at 09:00
  • Expressions may a way to go - see https://github.com/FluentValidation/FluentValidation/blob/master/src/FluentValidation/AbstractValidator.cs#L181 – Sir Rufo Feb 18 '20 at 09:05
  • Sir Rufo, I really would love to try your hint, but to be honest: I don't grasp it. Would you mind to give me a hint how to transform the GetValiAttriError method in order to be able to get the error message simply by calling GetValiAttriError(MyClassName.MyPropertyName) - that would be terrific – Fabianus Feb 18 '20 at 10:45

0 Answers0