Add Attributes to set the validation
This can of course easily be modified to work with some other scenario.
[AttributeUsage(AttributeTargets.Property)]
public class ContentAreaItemsMaxAttribute : ValidationAttribute
{
private readonly int _max;
public ContentAreaItemsMaxAttribute(int max)
{
_max = max;
}
public override bool IsValid(object value)
{
if ((value != null) && !(value is ContentArea))
{
throw new ValidationException("ContentAreaItemsMaxAttribute is intended only for use with ContentArea properties.");
}
var contentArea = value as ContentArea;
if (contentArea.Count > _max)
{
ErrorMessage = string.Format("OBS: You can only add {0} products to the block content area.", _max);
return false;
}
return true;
}
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
var result = base.IsValid(value, validationContext);
if (result != null && !string.IsNullOrEmpty(result.ErrorMessage))
{
result.ErrorMessage = string.Format("{0} {1}", validationContext.DisplayName, ErrorMessage);
}
return result;
}
}
Usage:
Use the Attribute:
[ContentAreaItemsMax(3)]
public virtual ContentArea SomeProperty{ get; set; }