JSF password confimation validation using ADF 11

razenha picture razenha · Sep 29, 2009 · Viewed 8.4k times · Source

How can I create a validator that validates if the user inputed the same values in the password field and the password confirmation field?

I did it in the managed bean, but I prefer to do it using a JSF validator...

The real question is, how to create a validator that access other JSF components other than the component being validated?

I am using ADF Faces 11.

Thanks...

Answer

McDowell picture McDowell · Sep 29, 2009

The real question is, how to create a validator that access other JSF components other than the component being validated?

Don't try to access the components directly; you'll regret it. JSF's validation mechanism work best at preventing junk from getting into the model.

You could use a different type of managed bean; something of the form:

/*Request scoped managed bean*/
public class PasswordValidationBean {
  private String input1;
  private String input2;
  private boolean input1Set;

  public void validateField(FacesContext context, UIComponent component,
      Object value) {
    if (input1Set) {
      input2 = (String) value;
      if (input1 == null || input1.length() < 6 || (!input1.equals(input2))) {
        ((EditableValueHolder) component).setValid(false);
        context.addMessage(component.getClientId(context), new FacesMessage(
            "Password must be 6 chars+ & both fields identical"));
      }
    } else {
      input1Set = true;
      input1 = (String) value;
    }
  }
}

This is bound using the method-binding mechanism:

<h:form>
  Password: <h:inputSecret
    validator="#{passwordValidationBean.validateField}"
    required="true" />
  Confirm: <h:inputSecret
    validator="#{passwordValidationBean.validateField}"
    required="true" />
  <h:commandButton value="submit to validate" />
  <!-- other bindings omitted -->
  <h:messages />
</h:form>

In future, you should be able to do this sort of thing using Bean Validation (JSR 303).