JSF Validator compare to Strings for Equality
How would you compare two string for equality in a JSF Validator?
if (!se开发者_运维知识库ttingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) {
save = false;
FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null);
}
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.
精彩评论