我正在尝试验证封装其他对象列表的对象,如下所示(为简洁起见缩短):
public class FormDTO {
private List<AttributeDTO> ruleAttributes;
// More attributes here
}
public class AttributeDTO {
private String value;
// More attributes here
}
我的验证器的片段如下:
for(AttributeDTO attributeDTO : attributes)
{
if(attributeDTO.getValue() == null || attributeDTO.getValue().length() == 0)
{
errors.reject("value", "value.isEmpty");
}
}
我的jsp包含以下内容:
<c:forEach items="${form.ruleAttributes}" var="ruleAttribute" varStatus="counter">
<tr>
<td>
<c:choose>
<c:when test="${ruleAttribute.isEditable}">
<form:input path="ruleAttributes[${counter.index}].value" value="${ruleAttribute.value}"/>
</c:when>
<c:otherwise>
<span class="derived">NotEditable</span>
</c:otherwise>
</c:choose>
</td>
<td>
<form:errors path="ruleAttributes[${counter.index}].value"/>
</td>
</tr>
</c:forEach>
如何为相关列表项显示相应的错误消息?总之,我希望“value.isEmpty”消息出现在具有空值的相关行的表格单元格中。
由于
答案 0 :(得分:3)
再次阅读Spring参考指南后,我可以自己回答这个问题。
要为此代码段显示相应的错误...
<form:errors path="ruleAttributes[${counter.index}].value"/>
...我需要修改我的验证码,如下所示:
for(int i = 0; i < ruleAttributes.size(); i++)
{
AttributeDTO attributeDTO = ruleAttributes.get(i);
if(attributeDTO.getValue() == null || attributeDTO.getValue().length() == 0)
{
errors.rejectValue("ruleAttributes[" + i + "].value", "value.isEmpty", "Value should not be empty");
}
}