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