2011-03-31 44 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