如何检查jsf组件在xhtml中是否有效

时间:2014-06-20 14:23:45

标签: jsf twitter-bootstrap-3 jstl

我正在使用bootstrap css制作一个忘记密码提醒的简单表单。如果密码未验证,则会显示错误并相应地突出显示输入。问题是当我第一次加载页面时,它说用户名已经无效。我该如何解决这个问题?

<h:form id="forgotPassword" styleClass="mar-top30 mar-bot30">
                    <div class="row">
                        <div class="col-md-4 col-md-offset-4">
                            <h3>Password reminder</h3>
                            <div class="input-group input-group-lg #{!username.valid ? 'has-error' : 'none'}  mar-top15 mar-bot15">
                                <span class="input-group-addon">
                                    <i class="fa fa-user"></i>
                                </span>
                                <h:inputText id="username" value="#{viewAccount.username}" styleClass="form-control input-lg" required="true" requiredMessage="Please enter your username" p:placeholder="Username">
                                    <f:validateLength maximum="20" minimum="3" />
                                    <f:validator validatorId="forgotPasswordValidator"/>
                                </h:inputText>
                            </div>
                            <h:panelGroup layout="block" rendered="#{username.valid}" styleClass="alert alert-danger alert-dismissable">
                                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                <h:message for="username"/>
                            </h:panelGroup>
                            <h:commandButton type="submit" value="Send Reset Link" action="#{viewAccount.forgotPassword()}" styleClass="btn btn-lg btn-default btn-block" />
                            <h:link outcome="login" styleClass="btn btn-lg btn-warning btn-block mar-top15"><i class="fa fa-reply"></i> Return to login</h:link>
                        </div>
                    </div>
                </h:form> 

1 个答案:

答案 0 :(得分:1)

您需要添加绑定到用户名并使用它来检查组件是否有效,或者

将方法添加到应用程序bean并在UI中使用

public static boolean isValid(String clientId) {
        UIComponent comp = FacesContext.getCurrentInstance().
                    getViewRoot().findComponent(clientId);
        if(comp instanceof UIInput) {
            return ((UIInput)comp).isValid();
        }
        throw new IllegalAccessError();
    }

在UI中

<h:panelGroup layout="block"
          rendered="#{facesUtil.isValid('forgotPassword:username')}" 
          styleClass="alert alert-danger alert-dismissable">
  <button type="button" class="close" 
            data-dismiss="alert" aria-hidden="true">&times;</button>
 <h:message for="username"/>
 </h:panelGroup>