我有一个联系表单,我有一些由bean验证验证的字段,如何在提交后返回bean验证错误消息?
例如:
<h:form>
<h:inputText id="name" value="#{contact.client.name}"></h:inputText>Name (Required)
<h:inputText id="email" value="#{contact.client.email}"></h:inputText>E-Mail (Required)
<h:inputText id="website" value="#{contact.client.website}"></h:inputText>Website (Optional)
<h:inputText id="text" value="#{contact.client.text}"></h:inputText>Message (Required):
<h:commandButton value="Send" action="#{contact.sendMessage}" >
<f:ajax execute="@form" render="@form"/>
</h:commandButton>
</h:form>
这就是我验证字段的方式:
// Client.java (model)
@NotNull(message="Please provide your name")
private String name;
@NotNull(message="Please provide your email")
@Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Invalid e-mail")
private String email;
@Pattern(regexp = "(http[s]?://|ftp://)?(www\\.)?[a-zA-Z0-9-\\.]+\\.([a-zA-Z]{2,5})$", message = "Not valid URL")
private String website;
@NotNull(message="Please provide your message")
private String text;
答案 0 :(得分:10)
使用for
属性附加到特定组件的<h:message>
,该属性应引用输入组件的id
:
<h:inputText id="name" value="#{contact.client.name}"></h:inputText>Name (Required)
<h:message for="name" />
<h:inputText id="email" value="#{contact.client.email}"></h:inputText>E-Mail (Required)
<h:message for="email" />
<h:inputText id="website" value="#{contact.client.website}"></h:inputText>Website (Optional)
<h:message for="website" />
<h:inputText id="text" value="#{contact.client.text}"></h:inputText>Message (Required):
<h:message for="text" />
或使用<h:messages/>
在一个地方展示所有内容:
<h:messages />
是的,bean验证消息也在那里结束。
不要忘记确保按钮的render
属性也包含它们。