2012-02-19 98 views
2

我有一個簡單的表單,獲取代碼然後顯示他的libelle,我添加了一個驗證bean,檢查代碼是否存在。 我的問題是我不能顯示代碼不存在時的錯誤消息。inputText驗證程序不顯示錯誤消息

下面是代碼:

test.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://java.sun.com/jsf/html" 
     xmlns:f="http://java.sun.com/jsf/core"> 
<h:head><title>Test</title> 
</h:head> 
<body class="bodyMain"> 

<h:form>   
    <h:panelGrid columns="3"> 
     <h:outputText value="Code: " /> 
     <h:inputText id="code" value="#{myBean.code}" 
      validator="#{myBean.validateCode}"> 
      <f:ajax execute="@this" render="libelle" listener="#{myBean.setLibelle()}"/> 
     </h:inputText> 
     <h:message for="code" style="color:red"/> 
    </h:panelGrid> 
    <h:panelGrid id="libelle" columns="2"> 
     <h:outputText value="Libelle: " /> 
     <h:outputText value="#{myBean.libelle}" /> 
    </h:panelGrid> 
</h:form>  

</body> 
</html> 

MyBean.java

@ManagedBean 
@ViewScoped 
public class MyBean implements java.io.Serializable{ 
    private static final long serialVersionUID = 1L; 

    private String code=""; 
    private String libelle=""; 

    public String getCode() { 
     return this.code; 
    } 

    public void setCode(String code) { 
     this.code=code; 
    }  

    public String getLibelle() { 
     return this.libelle; 
    } 

    public void setLibelle(String libelle) { 
     this.libelle=libelle; 
    } 

    public void setLibelle() { 
     if (code.compareTo("1")==0) 
      libelle="One"; 
     else 
      libelle=""; 
    } 

    public void validateCode(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException { 
     String code = (String)value; 
     if (code.compareTo("1") != 0) { 
      FacesMessage message = new FacesMessage("Code doesn't exist"); 
      throw new ValidatorException(message); 
     } 
    } 

} 

感謝你的幫助,以解決此問題

回答

3

你不通過<f:ajax>更新<h:message>組件。您需要給<h:message>一個id並將其包含在<f:ajax render>中。

<h:inputText id="code" value="#{myBean.code}" validator="#{myBean.validateCode}"> 
    <f:ajax execute="@this" render="libelle codeMessage" listener="#{myBean.setLibelle()}"/> 
</h:inputText> 
<h:message id="codeMessage" for="code" style="color:red"/> 

無關到具體問題,不初始化屬性爲空字符串。讓他們默認null。另外,比較對象應該使用equals()方法,而不是使用compareTo()。最後,使用包含所有可用值而不是輸入字段的下拉列表將更加便於用戶使用。

+0

它工作正常,非常感謝。 – 2012-02-20 09:45:48

+0

不客氣。 – BalusC 2012-02-20 13:36:49