【问题标题】:JSF Validator compare to Strings for EqualityJSF 验证器与字符串的相等性比较
【发布时间】:2011-07-27 00:39:48
【问题描述】:

如何在 JSF 验证器中比较两个字符串是否相等?

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

【问题讨论】:

    标签: validation jsf jsf-2


    【解决方案1】:

    使用普通的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,那么您可以使用 &lt;o:validateEquals&gt;。 “确认密码”的具体情况在&lt;o:validateEqual&gt; showcase上演示。

    【讨论】:

    • 嗨 BalusC,有没有其他方法可以在不绑定 inputSecret 组件的情况下做到这一点?
    • 您可以硬编码 ID 并传递它。例如。 &lt;f:attribute name="componentId" value="formid:passwordid" /&gt; 然后使用UIViewRoot#findComponent() 获取组件。然而,这只是笨拙的。为什么厌恶绑定?这对我来说没有意义。
    • 为组件添加绑定时是否有额外的开销(内存方面)?它可能很少,但只是一个问题。
    • 它非常小。它只是对内存中现有对象的又一次引用。引用字符串实际上可能更昂贵,因为该值不一定已经存在于字符串池中。
    • @Med:JSF 实用程序库 OmniFaces 有一个可重用的 &lt;o:validateEqual&gt; 组件,它正是这样做的:showcase-omnifaces.rhcloud.com/showcase/validators/…
    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 2016-08-10
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多