How validate two password fields by ajax?

Solution 1:

First of all, use a real Validator to validate the input. Don't do it in an action event method.

As to your concrete problem, you just need to specify the both fields in the execute attribute of the <f:ajax>, it namely defaults to the current component only. If you attach a validator to the first input and send the the value of the second input along as a <f:attribute>, then you will be able to grab it in the validator. You can use the binding attribute to bind the component to the view. This way you can pass its submitted value along by UIInput#getSubmittedValue().

Here's a kickoff example:

<h:outputLabel for="password" value="Password:" />
<h:inputSecret id="password" value="#{bean.password}" required="true">
    <f:validator validatorId="confirmPasswordValidator" />
    <f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
    <f:ajax event="blur" execute="password confirm" render="m_password" />
</h:inputSecret>
<h:message id="m_password" for="password" />

<h:outputLabel for="confirm" value="Password (again):" />
<h:inputSecret id="confirm" binding="#{confirmPassword}" required="true">
    <f:ajax event="blur" execute="password confirm" render="m_password m_confirm" />
</h:inputSecret>
<h:message id="m_confirm" for="confirm" />

(note that I added required="true" to both components and also note that you don't necessarily need to bind the confirm password component value to a managed bean property, it's worthless over there anyway)

with this validator

@FacesValidator("confirmPasswordValidator")
public class ConfirmPasswordValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String password = (String) value;
        String confirm = (String) component.getAttributes().get("confirm");

        if (password == null || confirm == null) {
            return; // Just ignore and let required="true" do its job.
        }

        if (!password.equals(confirm)) {
            throw new ValidatorException(new FacesMessage("Passwords are not equal."));
        }
    }

}