Search code examples
asp.net-mvc-3validationmodeldata-annotationscustomvalidator

MVC Model Custom Validation on IList


I have an IList attribute in my Model. I need to write a custom validation for that attribute (list)count which must be Greater than two.

public IList<AccountAddress> BulkOrderAddresses { get; set; }

Please help me....

Thanks In Advance


Solution

  • You could implement IValidatableObject Interface

    Something like this:

    public class MyObject : IValidatableObject
    {
         public IList<AccountAddress> BulkOrderAddresses { get; set; }
    
         public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
         {
              if(BulkOrderAddresses == null && !BulkOrderAddresses.Length > 2)
              {
                   yield return new ValidationResult("List should contain more than 2 items");
              }
         }
    }