Last active
January 6, 2016 08:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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