michael
michael

Reputation: 15302

IDataErrorInfo - Is there a collection is not empty validation attribute?

I don't know if I just can't find it or if it does not exist, but is there any validation attribute which checks if a collection is null/empty or not?

If not, is there any good resource out there on how to create my own validation attribute?

Upvotes: 4

Views: 1617

Answers (1)

Johan J v Rensburg
Johan J v Rensburg

Reputation: 322

When you use DataAnnotations as per default.kramer suggested you can create add a CustomValidation attribute and ValidationMethod to you collection property and class. See example below.

The important part of the ValidationMethod is that it is Static and you have to add the object that you're validating and the ValidationContext to the static method.

public class Order
{
[System.ComponentModel.DataAnnotations.Required( AllowEmptyStrings = false )]
public string Name
{
  get;
  set;
}

[System.ComponentModel.DataAnnotations.CustomValidation( typeof( Order ), "ValidateOrderLines" )]
public BindingList<OrderDetail> Lines
{
  get;
  set;
}

public static ValidationResult ValidateOrderLines( Order order, ValidationContext validationContext )
{
  ValidationResult result = new ValidationResult( "Lines are required!" );

  if ( order.Lines.Count != 0 )
    result = ValidationResult.Success;

  return result;
}

}

Upvotes: 2

Related Questions