简体   繁体   中英

Validating a List<T> To ensure list contains at list one Item with Data Annotations MVC C#

I'm trying to validate a generic list eg List<Sales> so that the list should contain at least one item added via check boxes.

Here is how I've tried to work this:

  public class SalesViewModel :IValidatableObject
    {

        [Required]
        public List<Sales> AllSales{ get; set; }


        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (AllSales.Length == 0)
                yield return new ValidationResult("Please pick one sales item");
        }
    }

Just want to know if this is the right approach to this kind of scenario.

You can also create a custom validation attribute , similar to the following:

public class EnsureOneItemAttribute : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    var list = value as IList;
    if (list != null)
    {
       return list.Count > 0;
    }
    return false;
  }     
}

And then apply it like:

[EnsureOneItemAttribute (ErrorMessage = "Please pick one sales item")]
public List<Sales> AllSales{ get; set; }

I know im a bit late, but this attribute allows you to set the min and max items

[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class EnsureMinimumElementsAttribute : ValidationAttribute
{
    private readonly int _min;
    private readonly int _max;

    public EnsureMinimumElementsAttribute(int min = 0, int max = int.MaxValue)
    {
        _min = min;
        _max = max;
    }

    public override bool IsValid(object value)
    {
        if (!(value is IList list))
            return false;

        return list.Count >= _min && list.Count <= _max;
    }
}

Usage -

Minumum, no max

[EnsureMinimumElements(min: 1, ErrorMessage = "Select at least one item")]

Min and Max

[EnsureMinimumElements(min: 1, max: 6, ErrorMessage = "You can only add 1 to 6 items to your basket")]

No min

[EnsureMinimumElements(max: 6, ErrorMessage = "You can add upto 6 items to your basket")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM