validationspring.net

Validating children of a collection property


I've inherited an application that heavily utilises Spring.NET for everything including validation. Right now I'm trying to figure out how to validate the children of a collection property, so given a structure like this:

public class ParentObj
{
    public virtual ICollection<ChildObj> Children { get; set; }
}

public class ChildObj
{
    public virtual string SomeField { get; set; }
}

How can I validate that ParentObj.Children is not null and contains more than 0 elements and then validate that every ChildObj.SomeField has a length of less than 100 chars? I'm picking through the documentation but am finding it hard to grasp the concept as there are no specific scenarios like mine, which is different to the above - but some guidance on how spring validates collections would be appreciated.

Right now I'm trying with the following (xml-based) configuration:

<v:group id="ParentObjValidator">
    <v:ref name="ChildObjValidator" />
    <v:condition test="Children != null and Children.Count > 0">
        <!-- message part -->
    </v:condition>
</v:group>

<v:group id="ChildObjValidator">
    <v:condition test="SomeField.Length <= 100" when="!string.IsNullOrEmpty(SomeField)">
        <!-- message part -->
    </v:condition>
</v:group>

Edit 1

Ok, I'm now getting somewhere (thanks to this) and have modified my config to something like:

<v:group id="ParentObjValidator">
    <v:collection context="Children" when="Children != null and Children.Count > 0">
        <v:ref name="ChildObjValidator" />
        <!-- message part -->
    </v:collection>
</v:group>

<v:group id="ChildObjValidator">
    <v:condition test="SomeField.Length <= 100" when="!string.IsNullOrEmpty(SomeField)">
        <!-- message part -->
    </v:condition>
</v:group>

Which it now seems to be happy with... however, my expected failures aren't being picked up so I'm not sure if the children are actually being validated (or my rules are wrong).


Solution

  • Got it! I was missing the include-element-errors="true" attribute on the collection type:

    <v:group id="ParentObjValidator">
         <v:collection context="Children" when="Children != null and Children.Count > 0" include-element-errors="true">
            <v:ref name="ChildObjValidator" />
            <!-- message part -->
        </v:collection>
    </v:group>
    
    <v:group id="ChildObjValidator">
        <v:condition test="SomeField.Length <= 100" when="!string.IsNullOrEmpty(SomeField)">
            <!-- message part -->
        </v:condition>
    </v:group>
    

    Seems to be up and running now.