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?
CodePudding user response:
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;
}