如何通过ajax验证两个密码字段?

Val*_*lva 15 passwords validation jsf jsf-2

我正在尝试用JSF验证两个密码字段,但直到现在还没有好处,我在google上搜索它,但一切都是关于JSF 1.2而且非常令人困惑,我正在使用JSF 2.0.

这就是我到目前为止所做的事情:

        <h:outputLabel for="password" value="Password:" />
        <h:inputSecret id="password"  value="#{register.user.password}"  >  
            <f:ajax    event="blur"   listener="#{register.validatePassword}" render="m_password" />
        </h:inputSecret>
        <rich:message id="m_password" for="password"/>

        <h:outputLabel for="password_2" value="Password (again):" />
        <h:inputSecret id="password_2"  value="#{register.user.password_2}"  >  
            <f:ajax    event="blur"     listener="#{register.validatePassword}" />
        </h:inputSecret>
Run Code Online (Sandbox Code Playgroud)

这就是我的控制器:

public void validatePassword() {
    FacesMessage message;

    if (!user.getPassword().equals(user.getPassword_2()) ){
        message = new FacesMessage(FacesMessage.SEVERITY_ERROR, null, "different password");
    }else{
        message = new FacesMessage(FacesMessage.SEVERITY_INFO, null, "ok");
    }

    FacesContext.getCurrentInstance().addMessage("form:password", message);
}
Run Code Online (Sandbox Code Playgroud)

伙计们好吗?

Bal*_*usC 19

首先,使用real Validator来验证输入.不要在动作事件方法中执行此操作.

至于你的具体问题,你只需要指定属性中的两个字段,它只是默认为当前组件.如果您将验证器附加到第一个输入并将第二个输入的值作为a发送,那么您将能够在验证器中获取它.您可以使用该属性将组件绑定到视图.这样您就可以传递其提交的值.execute<f:ajax><f:attribute>bindingUIInput#getSubmittedValue()

这是一个启动示例:

<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" />
Run Code Online (Sandbox Code Playgroud)

(请注意,我添加required="true"到两个组件中并且还注意到您不一定需要将确认密码组件值绑定到托管bean属性,无论如何它都没有价值)

使用此验证器

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

}
Run Code Online (Sandbox Code Playgroud)