3

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.

Oliver
  • 11,297
  • 18
  • 71
  • 121

1 Answers1

2

Rather than inheriting from Validate could you implement your own data annotation attribute to perform custom validation, as per this SO question?

How to create Custom Data Annotation Validators

Community
  • 1
  • 1
DaveRead
  • 3,371
  • 1
  • 21
  • 24
  • 2
    Thanks, I may do this, but I want to be able to work out whether my object will be accepted into the database before trying to save it: something like `if (Model.Validate().Count() == 0) {Database.Save(Model);}`. At the moment I have to `catch` an exception where trying to `Save()` to the database, which is horribly inefficient. – Oliver Apr 12 '12 at 15:34
  • 1
    If you adopt this approach you can still call Validator.TryValidateObject manually to check before submitting. – DaveRead Apr 12 '12 at 15:57