验证 IEnumerable(字符串集合)

Validation on IEnumerable (Collection of strings)

这只能通过自定义验证器完成吗?还是我遗漏了什么?只想对 ICollection<string> 属性 做一个简单的检查,看看它至少有一项。

尝试过但没有成功:

 [Required]
 [MinLength(1, ErrorMessage = "At least one Something is required")]
 public ICollection<string> Somethings { get; set; }

谢谢!

一个选项可能是向您的模型添加一个额外的 属性 来计算集合的长度,然后对其进行验证:

public ICollection<string> Somethings { get; set; }

[Range(1, 9999, ErrorMessage = "At least one Something is required")]
public int SomethingsCount => Somethings == null ? 0 : Somethings.Count;

这看起来很乱,因为您要向模型添加一个额外的 属性,但如果您很懒惰,那么这对您来说可能是个不错的选择。


更好的选择,根据 Denis 和 this answer 的评论,您可以定义自己的验证属性

public class RequiredCollectionAttribute : ValidationAttribute
{
    public override bool IsValid(object value) => value is IList list && list.Count > 0;
}

然后像这样使用它

[RequiredCollection(ErrorMessage = "At least one Something is required")]
public ICollection<string> Somethings { get; set; }

这是一个实际的实现示例:

class Program
{
    static void Main(string[] args)
    {
        var iceCream = new BuyIcecreamRequest { Tastes = new List<string>() { "Chocolate" } };
        var results = new List<ValidationResult>();
        bool isValid = Validator.TryValidateObject(iceCream, new ValidationContext(iceCream), results, true);
    }
}

public class MinimumCollectionLength : ValidationAttribute
{
    private readonly int _minimumCollectionLength;

    public MinimumCollectionLength(int minimumCollectionLength)
    {
        _minimumCollectionLength = minimumCollectionLength;
    }

    public override bool IsValid(object value)
    {
        var collection = value as ICollection;
        if (collection != null)
        {
            return collection.Count >= _minimumCollectionLength;
        }
        return false;
    }
}

public class BuyIcecreamRequest
{
    [Required]
    [MinimumCollectionLength(1, ErrorMessage = "At least one Taste is required")]
    public ICollection<string> Tastes { get; set; }
}

我还为此提供了另一个示例...

public class NotNullOrEmptyCollectionAttribute : ValidationAttribute
{
    private readonly int _length;

    public NotNullOrEmptyCollectionAttribute(int length)
    {
        _length = length;
    }

    public NotNullOrEmptyCollectionAttribute()
    {
        _length = -1;
    }

    public override bool IsValid(object value)
    {
        return value switch
        {
            ICollection collection when _length > -1 => collection.Count >= _length,
            ICollection collection => collection.Count != 0,
            _ => value is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext()
        };
    }
}

这可以用作

[NotNullOrEmptyCollection(1, ErrorMessage = "Please provide valid value for payment methods")]
public ICollection<PaymentMethod> PaymentMethods { get; set; }

[NotNullOrEmptyCollection]
public ICollection<PaymentMethod> PaymentMethods { get; set; }