Search code examples
.net-4.0validationattribute

Validate private properties using ValidationAttributes in .net 4


I have classes which get private properties set via the constructor.

I would then like to run the following code from a base class to check if the passed values are ok: ValidationContext context = new ValidationContext(this, null, null);

ValidationResults = new List();

if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject(this, context, ValidationResults, true))
{
    this.Success = false;
    this.StatusCode = CommandStatusCode.ValidationFailed;
    return false;
}
return true;

Problem is, the TryValidateObject only validates public properties. Is there any way of getting private properties validated?


Solution

  • I would use code contracts on your constructor's arguments.