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

前端之家收集整理的这篇文章主要介绍了jsf – 如何通过ajax验证两个密码字段?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用JSF验证两个密码字段,但直到现在都没有好处,我在google上搜索它,但是一切都是关于JSF 1.2,令人困惑的是,我使用的是JSF 2.0.

这是我到目前为止所做的

  1. <h:outputLabel for="password" value="Password:" />
  2. <h:inputSecret id="password" value="#{register.user.password}" >
  3. <f:ajax event="blur" listener="#{register.validatePassword}" render="m_password" />
  4. </h:inputSecret>
  5. <rich:message id="m_password" for="password"/>
  6.  
  7. <h:outputLabel for="password_2" value="Password (again):" />
  8. <h:inputSecret id="password_2" value="#{register.user.password_2}" >
  9. <f:ajax event="blur" listener="#{register.validatePassword}" />
  10. </h:inputSecret>

这是我的控制器:

  1. public void validatePassword() {
  2. FacesMessage message;
  3.  
  4. if (!user.getPassword().equals(user.getPassword_2()) ){
  5. message = new FacesMessage(FacesMessage.SEVERITY_ERROR,null,"different password");
  6. }else{
  7. message = new FacesMessage(FacesMessage.SEVERITY_INFO,"ok");
  8. }
  9.  
  10. FacesContext.getCurrentInstance().addMessage("form:password",message);
  11. }

任何想法家伙?

首先,使用真实的 Validator验证输入.不要在动作事件方法中执行.

对于你的具体问题,你只需要指定< f:ajax>的执行属性中的两个字段,它只默认为当前组件.如果您将验证器附加到第一个输入,并将第二个输入的值作为< f:attribute&gt ;.发送,那么您将能够在验证器中抓取它.您可以使用binding属性将组件绑定到视图.这样,您可以将其提交的价值通过UIInput#getSubmittedValue().

这是一个开球示例:

  1. <h:outputLabel for="password" value="Password:" />
  2. <h:inputSecret id="password" value="#{bean.password}" required="true">
  3. <f:validator validatorId="confirmPasswordValidator" />
  4. <f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
  5. <f:ajax event="blur" execute="password confirm" render="m_password" />
  6. </h:inputSecret>
  7. <h:message id="m_password" for="password" />
  8.  
  9. <h:outputLabel for="confirm" value="Password (again):" />
  10. <h:inputSecret id="confirm" binding="#{confirmPassword}" required="true">
  11. <f:ajax event="blur" execute="password confirm" render="m_password m_confirm" />
  12. </h:inputSecret>
  13. <h:message id="m_confirm" for="confirm" />

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

与此验证器

  1. @FacesValidator("confirmPasswordValidator")
  2. public class ConfirmPasswordValidator implements Validator {
  3.  
  4. @Override
  5. public void validate(FacesContext context,UIComponent component,Object value) throws ValidatorException {
  6. String password = (String) value;
  7. String confirm = (String) component.getAttributes().get("confirm");
  8.  
  9. if (password == null || confirm == null) {
  10. return; // Just ignore and let required="true" do its job.
  11. }
  12.  
  13. if (!password.equals(confirm)) {
  14. throw new ValidatorException(new FacesMessage("Passwords are not equal."));
  15. }
  16. }
  17.  
  18. }

猜你在找的Ajax相关文章