0

I'm trying to validate a filed based on another field in a list

public class CustomerModel
    {    
           public List<CustomerBrand> Brands { get; set; }

    }  
    }
    public class CustomerBrand
    {             
        public int Priority { get; set; }
        public bool Checked { get; set; }
     }

As per below if a checkbox is ticked then the value entered in the textbox must be greater than zero. Can anyone help out with a solution that keeps that validation in the model and out of the controller

enter image description here

I have made it work using this method but would like to be able to indicate the offending row.

  public class CustomerModel : IValidatableObject
    {
        public string Name { get; set; }

        public List<CustomerBrand> Brands { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
           foreach(var brand in Brands)
            {
                if(brand.Checked)
                {
                    if(brand.Priority < 1)
                    {
                        yield return new ValidationResult("Priority must be greater than 1");
                    }
                }
            }
        }
    }
JKerny
  • 488
  • 1
  • 3
  • 19
  • 1
    Possible duplicate of [attribute dependent on another field](https://stackoverflow.com/questions/3713281/attribute-dependent-on-another-field) – Marco Aug 14 '17 at 11:15

1 Answers1

0

How about something like this:

int x = 1;
foreach(var brand in Brands)
{
    if(brand.Checked)
    {
        if(brand.Priority < 1)
        {
            yield return new ValidationResult("Item " + x.ToString() + " - Priority must be greater than 1");
        }
    }
    x++;
}

If you have a way to refer to items by something other than position in the list, you could use that instead of x.

Ben Osborne
  • 1,412
  • 13
  • 20