如何验证字段并通过bean验证返回错误消息

如何验证字段并通过bean验证返回错误消息

本文介绍了JSF:如何验证字段并通过bean验证返回错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个联系表单,我有一些通过bean验证验证的字段,如何在提交后返回bean验证错误消息?

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?

例如:

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


推荐答案

使用通过附加到特定组件的属性,该属性应该引用输入组件的 id

Either use <h:message> which you attach to specific components by for attribute which should refer the id of the input component:

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

是的,bean验证消息也在那里结束。

Yes, bean validation messages also ends in there.

不要忘记确保按钮的渲染属性也包含它们。

Don't forget to ensure that the button's render attribute covers them as well.



  • JSF 2.0 tutorial with Glassfish and Eclipse - Hello World - The view

这篇关于JSF:如何验证字段并通过bean验证返回错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:19