Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Data Annotations Validation Manually and Object Graphs

Let's assume that I have two simple classes:

public class CustomerDetails
{
  [Required]
  public string Address
  {
    get;
    set;
  } 
}

public class Customer
{
   public Customer()
   {
     Details = new CustomerDetails();
   }

   [Required]
   public string Name
   {
     get;
     set;
   }
   public CustomerDetails Details
   {
     get;
     private set;
   } 
}

When I try to manually validate Customer class in a Console application in this way:

var customer = new Customer() { Name = "Conrad" };
var context = new ValidationContext(customer, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(customer, context, true);

Then -even though I chose to validate all properties of the customer instance- Validator just validates the Name property of the customer instance, but not the Address property of the Details.

Is this by design or am I missing something here? Moreover, if this is by design then is there a robust way to manually validate the full object graph decorated with validation attributes, including nested types instead of using validator for the whole object graph manually?

Please note that this is tested within a Console application and not an ASP.NET MVC application.

Kind regards.

like image 579
Kerem ÖZMAN Avatar asked Mar 09 '26 08:03

Kerem ÖZMAN


1 Answers

I had almost the same problem but with the collection of nested objects. I was able to resolve it by implementing IValidatableObject on a container class. In your case it's slightly easier. Something like this:

public class Customer : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
        var results = new List<ValidationResult>();
        Validator.TryValidateObject(this.Details, context, results);
        return results;
    }
}

Hope this helps.

like image 158
altso Avatar answered Mar 11 '26 08:03

altso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!