4

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.

1
  • 1
    Your approach is feasible, the following post answer is also optional. Commented Apr 29, 2020 at 6:55

3 Answers 3

7

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

If you're using C# 7.0+ you can make use of pattern matching. Syntax would be: return value is IList list && list.Count > 0;
6

Simplest version:

public class SalesViewModel
{

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

1 Comment

Love this, didn't know it existed. Why create your own validation attribute if you don't need to? +1
2

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")]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.