【问题标题】:JSF: How validate fields and return error messages by bean validation?JSF:如何通过 bean 验证验证字段并返回错误消息?
【发布时间】:2011-10-22 12:55:58
【问题描述】:

我有一个联系表单,并且我有一些通过 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;

【问题讨论】:

    标签: java jsf jsf-2 bean-validation


    【解决方案1】:

    要么使用&lt;h:message&gt;,通过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" />
    

    或使用&lt;h:messages/&gt; 将它们全部显示在一个位置:

    <h:messages />
    

    是的,bean 验证消息也到此结束。

    不要忘记确保按钮的render 属性也覆盖它们。

    另见:

    【讨论】:

    • 我按照您的教程进行操作,但是我遇到了一个奇怪的问题,我更新了我的帖子,请您看看吗?
    • 具体问题解决了吗?你的新问题是无关的。它看起来更像是一个 CSS 问题。
    • 是的,它是伙伴,感谢您的帮助。不过我会看看我的 CSS。
    • 它在您的教程中提到了它,但 javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL 需要在 web.xml 中设置为 context-param 以使 @NotNull bean 验证器正常工作。只是想知道为什么你的 bean 验证消息没有出现(就像我一样)
    猜你喜欢
    • 2017-08-15
    • 2013-11-19
    • 2023-03-30
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    相关资源
    最近更新 更多