I am using Validator.TryValidateObject()
to validate an object that uses data annotations. When the object is invalid, the code executes fine. However, if it is valid, a stackoverflow error is produced.
Here is my method:
public virtual IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
vc = new ValidationContext(this, null, null);
List<ValidationResult> a = new List<ValidationResult>();
Validator.TryValidateObject(this, vc, a,true);
foreach (var item in a)
yield return item;
if (Name == "Arbitary")
yield return new ValidationResult("Bad Name.", new[] { "Name" });
}
It seems that TryValidateObject
is internally calling my method Validate
also.
My goal with this method is to validate all the DataAnnotations for my object, and then add on some complex validation logic afterwards - so I assumed that TryValidateObject
would check data annotations, then afterwards I could place my own validation logic.
As it stands, my method works if the data is invalid - it will report the ValidationResults produced from the DataAnnotations, and also add a ValidationResult if the name is "Arbitary", but I get this stackoverflow if the data is valid.
Any ideas? How can I validate the data annotations of my object in a way that doesn't result in my own Validate
method being called? Alternatively, How do I resolve this stack overflow?
Note that my class implements the IValidatableObject
interface.