Skip to content

Instantly share code, notes, and snippets.

@andyjansson
Last active August 29, 2015 14:09
Show Gist options
  • Save andyjansson/6d51d18682f5a0d49c13 to your computer and use it in GitHub Desktop.
Save andyjansson/6d51d18682f5a0d49c13 to your computer and use it in GitHub Desktop.
LimitAttribute
public class LimitAttribute : ValidationAttribute
{
private int Limit {get; set;}
public LimitAttribute(int limit)
{
this.Limit = limit;
}
public override bool IsValid(object value)
{
if ((value != null) && !(value is ContentArea))
{
throw new ValidationException("LimitAttribute is intended only for use with ContentArea properties");
}
var contentArea = value as ContentArea;
if (contentArea != null && contentArea.Items.Count() > Limit)
{
ErrorMessage = "has too many items";
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;
}
}
[Limit(3)]
public virtual ContentArea MainContentArea { get; set; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment