1

I have the following code in my view model which is working correctly and puts a validation message on my view:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    yield return new ValidationResult("Required", new[] { "Insured.FirstName" });
}

However, I would like to reference the member name without using a string literal so I tried changing it to the following:

yield return new ValidationResult("Required", new[] { nameof(Insured.FirstName) });

This does not work. The validation message does not appear on my view. Is this not supported or am I doing this incorrectly?

Ryan Buening
  • 1,559
  • 2
  • 22
  • 60
  • 2
    Pretty sure `nameof(Insured.FirstName)` returns only, "FirstName". – Quantic May 31 '17 at 15:17
  • @Quantic do you know if it's possible to return the full "Insured.FirstName" using nameof? – Ryan Buening May 31 '17 at 15:21
  • 2
    Well I'm just searching around SO and finding people writing methods to construct the name for you, such as [this one](https://stackoverflow.com/a/39296258/5095502) or [this one](https://stackoverflow.com/a/36009266/5095502). In your case you could get by with `nameof(Insured) + "." + nameof(FirstName)`. – Quantic May 31 '17 at 15:25
  • 1
    See [this](https://stackoverflow.com/q/27898178/1997232). – Sinatr May 31 '17 at 15:25

1 Answers1

1

Thanks to the comments above I ended up putting this in a Utilities class:

public static class Utilities
{
    public static string GetPathOfProperty<T>(Expression<Func<T>> property)
    {
        string resultingString = string.Empty;
        var p = property.Body as MemberExpression;
        while (p != null)
        {
            resultingString = p.Member.Name + (resultingString != string.Empty ? "." : "") + resultingString;
            p = p.Expression as MemberExpression;
        }
        return resultingString;
    }
}

and then I can do the following:

yield return new ValidationResult("Required", new[] { Utilities.GetPathOfProperty(() => Insured.FirstName) });
Ryan Buening
  • 1,559
  • 2
  • 22
  • 60