Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g 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.

like image 375
lacoder Avatar asked Oct 20 '25 15:10

lacoder


2 Answers

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; }
like image 199
Zeeshan Avatar answered Oct 23 '25 05:10

Zeeshan


Simplest version:

public class SalesViewModel
{

    [Required, MinLength(1, ErrorMessage = "Please pick one sales item")]
    public List<Sales> AllSales{ get; set; }
}
like image 30
stefan.seeland Avatar answered Oct 23 '25 04:10

stefan.seeland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!