java JSF:如何通过 bean 验证验证字段并返回错误消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6985049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSF: How validate fields and return error messages by bean validation?
提问by Valter Silva
I have a contact form and I have some fields that are validated by bean validation, how could I return bean validation error messages after submitting?
我有一个联系表单,我有一些通过 bean 验证验证的字段,提交后如何返回 bean 验证错误消息?
For example:
例如:
<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>
This is how I'm validating my fields:
这就是我验证字段的方式:
// 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;
回答by BalusC
Either use <h:message>
which you attach to specific components by for
attribute which should refer the id
of the input component:
要么使用<h:message>
您通过for
属性附加到特定组件的使用,该属性应引用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" />
or use <h:messages/>
to display them all at a single place:
或用于<h:messages/>
将它们全部显示在一个地方:
<h:messages />
Yes, bean validation messages also ends in there.
是的,bean 验证消息也在那里结束。
Don't forget to ensure that the button's render
attribute covers them as well.
不要忘记确保按钮的render
属性也涵盖它们。