LSTANCZYK
9/25/2017 - 1:32 AM

ValidationEPi01.cs

/// <summary>    
/// Limit numbers of items in ContentArea
/// Add [MaxItemCount(2)] to a prop-definition limits number of items;
///   [Display(Name = "Articles")]
///   [MaxItemCount(2)]
///   public virtual ContentArea ArticlesContentArea { get; set; }
/// </summary>  
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class MaxItemCount : ValidationAttribute
{
    private readonly int _limit;
    public int Limit
    {
        get { return _limit; }
    }

    public MaxItemCount(int limit)
    {
        _limit = limit;
    }
    
    public override bool IsValid(object value)
    {
        return ValidateContentArea(value as ContentArea);
    }

    private bool ValidateContentArea(ContentArea contentArea)
    {
        if (contentArea == null || contentArea.Items == null || !contentArea.Items.Any())
            return true;

        return contentArea.Items.Count <= Limit;
    }

    public override string FormatErrorMessage(string name)
    {
        return "Too many items in contentarea :(";
    }
}