如何验证JSF中的多个字段?

时间:2013-12-29 05:41:05

标签: validation jsf

我正在JSF中进行验证,我看到很多非常基本的逻辑示例。坦率地说,我将它们放在HelloWorld示例所在的同一类别中。我无法想象在xhtml文件中放置错误消息,为每个验证字段使用单独的验证方法或使用bean验证。

我想要做的是,在backing bean上有一个方法,它将为每个字段执行验证,记录由i18n属性文件中的键驱动的错误消息。

可以这样做吗?如果是这样,我们如何将该方法注册为验证方法,如何获取提交的字段值以进行评估,以及如何注册错误消息?

1 个答案:

答案 0 :(得分:0)

<h:inputText id="username" value="#{bean.username}" label="UserName" binding="#{bean.component}"/>
<h:message for="username" />
<h:commandButton value="Submit" action="#{bean.actionMethod}" />

在你的bean类中,

private UIComponent component;

public UIComponent getComponent() {
    return component;
}

public void setComponent(UIComponent component) {
    this.component = component;
}

public String actionMethod() {
    if (!validate()) {
        return null;
    }
    // do your action method logic
}

private boolean validate() {
    FacesContext context = FacesContext.getCurrentInstance();

    //do validation for your fields and add to faces messages
    FacesMessage msg = new FacesMessage(severity, summary, detail);
    context.addMessage(component.getClientId(), msg);

    // do for other fields

    return status;
}

请参阅此内容以获取组件客户端ID

How to add a message to a specific component from JSF backing bean

相关问题