0

I am implementing IValidatableObject. In my Validate function, I want to return multiple ValidationResults. How is the best way to go about this?

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {


            List<ValidationResult> validationResults = new List<ValidationResult>();

            if (QuantityTraded < 1 || QuantityTraded > MaxTradeQuantity )
            {
                validationResults.Add(new ValidationResult($"There must be a quantity greater than zero and less than {MaxTradeQuantity}"));
            }
            if (TotalAmount > TotalPortfolioCash)
            {
                validationResults.Add(new ValidationResult($"There is currently not enough money in the Portfolio ({TotalPortfolioCash}) for this order."));
            }

            if(validationResults.Any() && validationResults.Count > 0)
            {
                return validationResults;
            } 
        }

This does not seem like a good approach, since if there are no ValidationResults, it should not return anything. If I go back to using yield,

yield return new ValidationResult($"There is currently not enough money in the Portfolio ({TotalPortfolioCash}) for this order.");

I can only return one ValidationResult at a time, instead of multiple. Is there a better way to go about this?

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
HoboJeff
  • 101
  • 1
  • 1
  • 8

1 Answers1

1

You can try to remove if(validationResults.Any() && validationResults.Count > 0),no matter you added data to validationResults or not,you should return IEnumerable<ValidationResult> in Validate` method:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {


            List<ValidationResult> validationResults = new List<ValidationResult>();

            if (QuantityTraded < 1 || QuantityTraded > MaxTradeQuantity )
            {
                validationResults.Add(new ValidationResult($"There must be a quantity greater than zero and less than {MaxTradeQuantity}"));
            }
            if (TotalAmount > TotalPortfolioCash)
            {
                validationResults.Add(new ValidationResult($"There is currently not enough money in the Portfolio ({TotalPortfolioCash}) for this order."));
            }

            return validationResults;
        }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • But if there are no errors, it is still returning an empty list...? Won't that mess up the validation? – HoboJeff Dec 25 '22 at 12:23
  • Your `validate` method needs you to return `IEnumerable` type data.You can also refer to the [link](https://stackoverflow.com/questions/3400542/how-do-i-use-ivalidatableobject). – Yiyi You Dec 26 '22 at 01:26