title: How can I access the collection item being validated when using RuleForEach?
body: <p>I'm using FluentValidation to validate an object, and because this object has a collection member I'm trying to use <code>RuleForEach</code>. For example, suppose we have <code>Customer</code> and <code>Orders</code>, and we want to ensure that no customer order has a total value that exceeds the maximum allowed for that customer:</p>
  
  <pre><code>this.RuleForEach(customer =&gt; customer.Orders)
      .Must((customer, orders) =&gt; orders.Max(order =&gt; order.TotalValue) &lt;= customer.MaxOrderValue)
  </code></pre>
  
  <p>So far, so good. However, I also need to record additional information about the context of the error (e.g. where in a data file the error was found). I've found this quite difficult to achieve with FluentValidation, and my best solution so far is to use the <code>WithState</code> method. For example, if I find that the customer's address details are incorrect, I might do something like this:</p>
  
  <pre><code>this.RuleFor(customer =&gt; customer.Address)
      .Must(...)
      .WithState(customer =&gt; GetErrorContext(customer.Address))
  </code></pre>
  
  <p>(where <code>GetErrorContext</code> is a method of mine to extract the relevant details.</p>
  
  <p>Now the problem I have is that when using <code>RuleForEach</code>, the method signature assumes that I'll provide an expression that references the <em><code>Customer</code></em>, not the particular <code>Order</code> that caused the validation failure. And I seem to have no way to tell which order had a problem. Hence, I can't store the appropriate context information.</p>
  
  <p>In other words, I can only do this:</p>
  
  <pre><code>this.RuleForEach(customer =&gt; customer.Orders)
      .Must((customer, orders) =&gt; orders.Max(order =&gt; order.TotalValue) &lt;= customer.MaxOrderValue)
      .WithState(customer =&gt; ...)
  </code></pre>
  
  <p>...when I really wanted to do this:</p>
  
  <pre><code>this.RuleForEach(customer =&gt; customer.Orders)
      .Must((customer, orders) =&gt; orders.Max(order =&gt; order.TotalValue) &lt;= customer.MaxOrderValue)
      .WithState(order =&gt; ...)
  </code></pre>
  
  <p>Is there really no way to access the details (or even the index) of the collection item(s) that failed?</p>
  
  <p>I suppose another way of looking at it is that I want <code>WithState</code> to have an equivalent <code>WithStateForEach</code>...</p>