2012-09-28 168 views
1

我試圖只顯示一個兩個所需的字段。 目前有兩個錯誤消息,如果兩個字段都是空的。我想實現只有一個字段爲空的情況下只有一條消息。JSF兩個所需輸入字段的一個錯誤消息

的代碼看起來是這樣的:

<x:inputText 
    value="#{bean.proxyUrl}" 
    id="idProxyUrl" 
    required="true" 
    /> 
<x:outputText value=":" /> 
<x:inputText 
    value="#{bean.proxyPort}" 
    id="idProxyPort" 
    required="true" 
    /> 
<x:message for="idProxyUrl" errorClass="errorMessage" style="margin-left: 10px;" /> 
<x:message for="idProxyPort" errorClass="errorMessage" style="margin-left: 10px;" /> 

我能做些什麼,我只得到一個消息,無論該領域的一個或兩個是空的。

+0

'x:'前綴不可識別爲任何已知的JSF組件庫。我是否可以假定它是使用URI「http:// java.sun.com/jsf/html」設置的標準JSF HTML組件? (如果是這樣,你爲什麼要改變世界上每個人都使用的標準'h:'前綴?) – BalusC

+1

這可能會幫助你一點... http://stackoverflow.com/q/10007438/617373 – Daniel

+0

'x :'指向'http:// myfaces.apache.org/tomahawk' – Przemek

回答

2

您可以爲檢查第一個組件的SubmittedValue的第二個組件指定一個特殊的驗證程序。我爲PasswordValidator做了類似的檢查相應的確認密碼字段。

@FacesValidator("passwordValidator") 
public class PasswordValidator implements Validator {  

    @Override 
    public void validate(FacesContext context, UIComponent component, 
      Object value) throws ValidatorException { 


     String password = (String) value; 


     UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm"); 
     String confirm = (String) confirmComponent.getSubmittedValue(); 

     if (password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) { 
      FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please confirm password", null); 
      throw new ValidatorException(msg); 
     } 


     if (!password.equals(confirm)) { 
      confirmComponent.setValid(false); 
      FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The entered passwords do not match", null); 
      throw new ValidatorException(msg); 
     } 


    } 

您必須檢查其他組件的提交值的原因是驗證程序在生命週期的過程驗證階段被調用。直到此階段完成並且每個提交的值已通過驗證後,纔會應用所提交的值。

+0

謝謝。經過一些小小的改變,因爲這些領域不一定是平等的,這就是幫助。我對JSF相當陌生,需要非常學習! – Przemek