我知道这个问题有点老了,但也许有人来寻找答案。
我不知道将属性应用于集合项的通用方法,但是对于特定的字符串长度示例,我使用了以下内容:
public class StringEnumerationLengthValidationAttribute : StringLengthAttribute
{
public StringEnumerationLengthValidationAttribute(int maximumLength)
: base(maximumLength)
{ }
public override bool RequiresValidationContext { get { return true; } }
public override bool IsValid(object value)
{ return false; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var e1 = value as IEnumerable<string>;
if (e1 != null) return IsEnumerationValid(e1, validationContext);
return ValidationResult.Success; // what if applied to something else than IEnumerable<string> or it is null?
}
protected ValidationResult IsEnumerationValid(IEnumerable<string> coll, ValidationContext validationContext)
{
foreach (var item in coll)
{
// utilize the actual StringLengthAttribute to validate the items
if (!base.IsValid(item) || (MinimumLength > 0 && item == null))
{
return new ValidationResult(base.FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
应用如下,每个收藏项要求 4-10 个字符:
[StringEnumerationLengthValidation(10, MinimumLength=4)]
public ICollection<string> Sample { get; set; }