Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Created September 25, 2017 01:32
Show Gist options
  • Save LSTANCZYK/c45c31cec09e3c3fcc006552c084d534 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/c45c31cec09e3c3fcc006552c084d534 to your computer and use it in GitHub Desktop.
/// <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 :(";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment