Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF Validator compare to Strings for Equality

How would you compare two string for equality in a JSF Validator?

if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) {
    save = false;
    FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null);
}
like image 580
c12 Avatar asked Mar 31 '11 15:03

c12


1 Answers

Use a normal Validator and pass the value of first component as attribute of second component.

<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!)

with

@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."));
        }
    }

}

If you happen to use JSF utility library OmniFaces, then you can use <o:validateEquals> for this. The exact case of "confirm password" is demonstrated on <o:validateEqual> showcase.

like image 102
BalusC Avatar answered Nov 03 '22 06:11

BalusC