JSF Validator与Strings for Equality相比较

时间:2011-03-31 15:40:12

标签: validation jsf jsf-2

如何在JSF Validator中比较两个字符串的相等性?

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

1 个答案:

答案 0 :(得分: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上展示。