0

When a base class has a property decorated with validation attributes, is it possible to add more validation attributes within a derived class?

In the following example, Property has both attributes, but validation using the attribute on the base class doesnt seem to work.

public abstract class BaseClass
{
    [StringLength(2, MinimumLength = 1)]
    public virtual string Property { get; set; }
}

public class DerivedClass : BaseClass
{
    [Required]
    public override string Property { get; set; }
}

var obj = new DerivedClass
{
    Property = "123" // Length is greater than max length of 2
};

var requiredAttr = obj.GetType()
    .GetProperty(nameof(obj.Property))
    .GetCustomAttribute<RequiredAttribute>(); // Attribute retrieved - it exists

var stringLengthAttr = obj.GetType()
    .GetProperty(nameof(obj.Property))
    .GetCustomAttribute<StringLengthAttribute>(); // // Attribute retrieved - it exists

var results = new List<ValidationResult>();
Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), results); 
// No validation errors

devklick
  • 2,000
  • 3
  • 30
  • 47

1 Answers1

0

Turns out it's as simple as adding an extra parameter to the Validator.TryValidateObject call:

var context = new ValidationContext(obj, null, null);
Validator.TryValidateObject(obj, context, results, validateAllProperties: true); // No validation errors

Doing this now includes the attribute validation on the properties from the base class.

Credit to this answer.

devklick
  • 2,000
  • 3
  • 30
  • 47