Note that there are some explanatory texts on larger screens.

plurals
  1. POPass an element of the object to a FluentValidation SetValidator's constructor
    primarykey
    data
    text
    <p>I'm using FluentValidation to validate a collection inside of an object, comparing an element of the collection items to an element of the parent object.</p> <p>The goal output is to receive ValidationFailures for each failed item in the collection, not just to fail the collection. </p> <p>I have a software order, containing a list of software items. If the order is for a legacy system, the selected software can only be legacy software, and vice-versa, a non-legacy system can only have non-legacy software.</p> <p>My model:</p> <pre><code>public class SoftwareOrder { public bool IsLegacySystem; public List&lt;SoftwareItem&gt; Software; (...other fields...) } public class SoftwareItem { public bool Selected; public bool IsLegacySoftware; public int SoftwareId; } </code></pre> <p>Validators:</p> <pre><code>public class SoftwareOrderValidator : AbstractValidator&lt;SoftwareOrder&gt; { public SoftwareOrderValidator() { (..other rules..) When(order =&gt; order.IsLegacySystem == true, () =&gt; { RuleForEach(order =&gt; order.SoftwareItem) .SetValidator(new SoftwareItemValidator(true)); }); When(order =&gt; order.IsLegacySystem == false, () =&gt; { RuleForEach(order =&gt; order.SoftwareItem) .SetValidator(new SoftwareItemValidator(false)); }); } } public class SoftwareItemValidator : AbstractValidator&lt;SoftwareItem&gt; { public SoftwareItemValidator(bool IsLegacySystem) { When(item =&gt; item.Selected, () =&gt; { RuleFor(item =&gt; item.IsLegacySoftware) .Equal(IsLegacySystem).WithMessage("Software is incompatible with system"); }); } } </code></pre> <p>As you can see, I'm accomplishing this by having a When for each condition. It works, but it violates DRY and is not practical to use in a situation with more than just two conditions.</p> <p>I'd ideally like to have a single RuleForEach that could do this, no Whens needed, something like:</p> <pre><code>RuleForEach(order =&gt; order.SoftwareItem) .SetValidator(new SoftwareItemValidator(order =&gt; order.IsLegacySystem)); </code></pre> <p>But I can't see any way to pass IsLegacySystem into that constructor.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload