我正在尝试使用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>
这是我的控制器:
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,"ok"); } FacesContext.getCurrentInstance().addMessage("form:password",message); }
任何想法家伙?
首先,使用真实的
原文链接:https://www.f2er.com/ajax/160115.htmlValidator
验证输入.不要在动作事件方法中执行.
对于你的具体问题,你只需要指定< f:ajax>的执行属性中的两个字段,它只默认为当前组件.如果您将验证器附加到第一个输入,并将第二个输入的值作为< f:attribute> ;.发送,那么您将能够在验证器中抓取它.您可以使用binding属性将组件绑定到视图.这样,您可以将其提交的价值通过UIInput#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" />
(请注意,我将两个组件都添加了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.")); } } }