3

Is it possible to specify field name using some strongly-typed way (lambda?) in such situation:

public class Demo : IValidatableObject
{
    public string DemoField {get; set;}

    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
    {
        if (<...>)
        {
            yield return new ValidationResult("Some validation message", new string[] { "DemoField" }); // <-- Here
        }
    }

}

When field name is specified in string it can't be refactored, for example.

artvolk
  • 9,448
  • 11
  • 56
  • 85

2 Answers2

4

I am not aware of any "built-in" way. But you could use LINQ expressions to do something like this:

Expression<Func<Demo, string>> lambda = (Demo d) => d.DemoField;
string demoFieldName = ((System.Linq.Expressions.MemberExpression)lambda.Body).Member.Name;
yield return new ValidationResult("Some validation message", new string[] { demoFieldName });

This way you have no hard-coded strings, and refactoring will work.

Eilon
  • 25,582
  • 3
  • 84
  • 102
1

Read my answer on this question here:

https://stackoverflow.com/a/15396656/643761

You would use it like this:

yield return new ValidationResult("Some Error.", GetFieldNames(() => new object[] { this.DemoField }));
Community
  • 1
  • 1
Simcha Khabinsky
  • 1,970
  • 2
  • 19
  • 34