【问题标题】:Validation on IEnumerable (Collection of strings)验证 IEnumerable(字符串集合)
【发布时间】:2020-05-26 15:07:05
【问题描述】:

这只能通过自定义验证器完成,还是我遗漏了什么?只想简单检查一下 ICollection<string> 属性是否至少包含一项。

试过了,没有运气:

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

谢谢!

【问题讨论】:

标签: c# asp.net-core blazor blazor-client-side


【解决方案1】:

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

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; }
}

【讨论】:

  • 感谢您回答马可。如果它变得相关,我可能会在未来有更多选择切换到类似的东西。
【解决方案2】:

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

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; }

【讨论】:

  • 我选择了这个。只是想确保没有任何我错过的内置方法,但是这个简短而简单,是我现在需要的。谢谢巴斯
【解决方案3】:

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

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; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多