6

came across an issue with validation of complex classes in ASP.NET MVC4 using DataAnnotation.

Let's have a following model (simplified)

public class Customer
{
   [Required]
   [StringLength(8, MinimumLength = 3)]        
   public string UserName { get; set; }

   [Required]
   [StringLength(8, MinimumLength = 3)]
   public string DisplayName { get; set; }
}


public class Order
{
    public Customer customer { get; set; }
}

Then I try to validate an instance of this model in my controller:

// CREATE A DUMMY INSTANCE OF THE MODEL 
Customer cust = new Customer();
cust.UserName = "x";
cust.DisplayName = "x";

Order orderModel = new Order();
orderModel.customer = cust;

// VALIDATE MODEL
TryValidateModel(orderModel); // ModelState.IsValid is TRUE (which is incorrect)
TryValidateModel(cust); // ModelState.IsValid is FALSE (whic is correct}

Validation of orderModel should fail as the cust.UserName has only 1 character, but 3 are required by the Model. Same applies to cust.DisplayName. But when I validate a pure Customer class then it fails as expected.

Any idea what's wrong?

thanks

Jiri

Jiri Matejka
  • 106
  • 3
  • 1
    As far as I know you can't validate nested objects like that, maybe use a custom validator – saj Aug 30 '12 at 13:20
  • 1
    It seems data annotation validation doesn't run validation of nested objects by default. Simmilar post here http://stackoverflow.com/questions/2493800/how-can-i-tell-the-data-annotations-validator-to-also-validate-complex-child-pro – petro.sidlovskyy Aug 30 '12 at 13:30

1 Answers1

2

DataAnnotations won't dig into your objects on it's own. You have two choices:

1--Write a custom validator to check child properties

2--Create a view model with populated with the simple properties decorated with data annotations

Forty-Two
  • 7,535
  • 2
  • 37
  • 54