2011-03-31 41 views
5

如何比較JSF Validator中的兩個字符串是否相等?JSF Validator與Strings for Equality的比較

if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) { 
    save = false; 
    FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null); 
} 

回答

17

使用正常Validator並通過第一分量的值作爲第二成分的屬性。

<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true" 
    requiredMessage="Please enter password" validatorMessage="Please enter at least 8 characters"> 
    <f:validateLength minimum="8" /> 
</h:inputSecret> 
<h:message for="password" /> 

<h:inputSecret id="confirmPassword" required="#{not empty passwordComponent.value}" 
    requiredMessage="Please confirm password" validatorMessage="Passwords are not equal"> 
    <f:validator validatorId="equalsValidator" /> 
    <f:attribute name="otherValue" value="#{passwordComponent.value}" /> 
</h:inputSecret> 
<h:message for="confirmPassword" /> 

note that binding in above example is as-is; you shouldn't bind it to a bean property!

@FacesValidator(value="equalsValidator") 
public class EqualsValidator implements Validator { 

    @Override 
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { 
     Object otherValue = component.getAttributes().get("otherValue"); 

     if (value == null || otherValue == null) { 
      return; // Let required="true" handle. 
     } 

     if (!value.equals(otherValue)) { 
      throw new ValidatorException(new FacesMessage("Values are not equal.")); 
     } 
    } 

} 

如果你碰巧使用JSF工具庫OmniFaces,那麼你可以使用<o:validateEquals>這一點。在<o:validateEqual> showcase上顯示「確認密碼」的確切情況。

+0

嗨BalusC,有沒有其他的方式來做到這一點,而無需綁定inputSecret組件? – c12 2011-04-03 02:58:25

+0

您可以對ID進行硬編碼並將其傳遞給它。例如。 ''然後使用'UIViewRoot#findComponent()'獲取組件。然而這只是笨拙的。爲什麼反對約束?這對我沒有意義。 – BalusC 2011-04-03 02:59:29

+0

當爲組件添加綁定時,沒有額外的開銷(內存明智)嗎?它可能很小,但只是一個問題。 – c12 2011-04-03 06:35:54