我正在使用Omnifaces <o:validateBean />
使用具有类级别约束的 JSR303 bean 验证。
整个事情运作得很好。验证消息显示在 Primefaces <p:messages />
中成分。现在我想知道是否可以将错误消息缩小到更精确的组件(即特定元素上的 <p:message />
标签)?在下面的示例中,我想将错误消息定向到 <p:message />
组件 id="id_msg_anniversary"
(或者如果可能的话,同时发送给 id="id_msg_anniversary"
和 id="id_msg_wedding"
)。
我的目的之一是通过 bean 验证来验证所有内容,而不是使用 <o:validateOrder />
或<o:validateMultiple />
.
@DayIsBeforeAnniversary
@Entity
public class Person implements Serializable
{
@Temporal(TemporalType.DATE)
private Date weddingDay;
@Temporal(TemporalType.DATE)
private Date silverWeddingAnniversary;
...
}
<p:messages id="id_messages" />
<h:outputLabel value="Wedding Day" />
<p:message id="id_msg_wedding" display="icon" for="id_wedding" />
<p:calendar
id="id_wedding"
value="#{personController.person.weddingDay}"> <br />
<h:outputLabel value="Silver Wedding Anniversary" />
<p:message id="id_msg_anniversary" display="icon" for="id_anniversary" />
<p:calendar
id="id_anniversary"
value="#{personController.person.silverWeddingAnniversary}" /> <br/>
<p:commandButton
value="test"
action="#{personController.navigate()}"
update="@all"/>
<o:validateBean value="#{personController.person}" />
public class DayIsBeforeAnniversaryValidator implements ConstraintValidator<DayIsBeforeAnniversary, Person>
{
@Override
public boolean isValid(Person person, ConstraintValidatorContext context)
{
return person == null
|| person.getWeddingDay() == null
|| person.getSilverWeddingAnniversary() == null
|| person.getWeddingDay().before(person.getSilverWeddingAnniversary());
}
...
}
public @interface DayIsBeforeAnniversary { ... }
为了澄清,我可以附加更多代码。
最佳答案
<o:validateBean>
将其消息与 <h:form>
相关联。因此,您需要做的就是确保您有一个 <p:message for="formId">
在所需的地方。请注意,您可以拥有多个。下面是一个启动示例。
<h:form id="formId">
<p:inputText id="foo" ... />
<p:message for="foo" />
<p:message for="formId" />
...
<p:inputText id="bar" ... />
<p:message for="bar" />
<p:message for="formId" />
...
<o:validateBean ... />
</h:form>
但是,我确实同意这不是最优雅的解决方案,与 ValidateMultipleFields
的成员相比肯定不是。有一个有用的家庭showMessageFor
属性用于目的。不幸的是,在 <o:validateBean>
上实现它在技术上相当复杂。同样,因为从技术上讲,BV 约束违规错误和 JSF 输入字段之间没有直接关系,因此必须根据 bean 属性和 JSF 组件树手动检查,这不完全是单行工作。
关于jsf - Omnifaces validateBean : attach message to specific component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982491/