Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save elizabeth-young/5875146 to your computer and use it in GitHub Desktop.
Save elizabeth-young/5875146 to your computer and use it in GitHub Desktop.
Validation attribute for ensuring a collection has a minimum and maximum length
public class CollectionMinMaxLengthValidationAttribute : ValidationAttribute
{
const string errorMessage = "{0} must contain at least {1} item(s).";
const string errorMessageWithMax = "{0} must contain between {1} and {2} item(s).";
int minLength;
int? maxLength;
public CollectionMinMaxLengthValidationAttribute(int min)
{
minLength = min;
maxLength = null;
}
public CollectionMinMaxLengthValidationAttribute(int min, int max)
{
minLength = min;
maxLength = max;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
if (maxLength != null)
{
return string.Format(errorMessageWithMax, name, minLength, maxLength.Value);
}
return string.Format(errorMessage, name, minLength);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null && minLength == 0)
{
return ValidationResult.Success;
}
if (value == null && minLength > 0)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
var collection = ((IEnumerable)value).Cast<object>().ToList();
if (collection.Count() >= minLength && (maxLength == null || collection.Count() <= maxLength))
{
return ValidationResult.Success;
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment