验证集合 children 属性

Validating children of a collection property

我继承了一个应用程序,该应用程序大量使用 Spring.NET 来处理包括验证在内的所有事情。现在我正在尝试弄清楚如何验证集合 属性 的 children,所以给出这样的结构:

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

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

如何验证 ParentObj.Children 不为空且包含超过 0 个元素,然后验证每个 ChildObj.SomeField 的长度是否小于 100 个字符?我正在浏览文档,但发现很难理解这个概念,因为没有像我这样的特定场景,这与上面的场景不同——但是一些关于如何 spring 验证集合的指导将不胜感激。

现在我正在尝试以下 (xml-based) 配置:

<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>

编辑 1

好的,我现在有所进展 (thanks to this) 并将我的配置修改为:

<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>

它现在似乎很满意......但是,我预期的失败没有被拾起所以我不确定 children 是否真的被验证(或者我的规则是错误的).

知道了!我缺少集合类型的 include-element-errors="true" 属性:

<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>

似乎起床了 运行 现在。