Created
September 25, 2017 01:34
-
-
Save LSTANCZYK/dd8665d95a740f9c674ea0a711f22ddb to your computer and use it in GitHub Desktop.
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 sealed class CollectionMinimumLengthAttribute : ValidationAttribute | |
{ | |
private const string ErrorMessageWithMax = "{0} must contain between {1} and {2} item(s)."; | |
private readonly int _minLength; | |
public CollectionMinimumLengthAttribute(int min) | |
{ | |
_minLength = min; | |
MaxLength = null; | |
ErrorMessage = "{0} must contain at least {1} item(s)."; | |
} | |
public CollectionMinimumLengthAttribute(int min, int max) | |
: this(min) | |
{ | |
_minLength = min; | |
MaxLength = max; | |
} | |
public int MinLength | |
{ | |
get { return _minLength; } | |
} | |
public int? MaxLength { get; private set; } | |
//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); | |
} | |
public override bool IsValid(object value) | |
{ | |
var list = value as IEnumerable<object>; | |
if (list != null && list.Count() >= _minLength && (MaxLength == null || list.Count() <= MaxLength)) | |
{ | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment