2009-09-29 47 views
3

如何创建一个验证器来验证用户是否在密码字段和密码确认字段中输入了相同的值?使用ADF的JSF密码验证验证11

我做到了在托管bean,但我更喜欢使用JSF验证做...

真正的问题是,如何创建访问除组件以外的其他JSF组件的验证程序所验证?

我使用的ADF Faces 11

谢谢...

回答

4

真正的问题是,如何建立有效的被访问成分以外的其他JSF组件的验证程序?

不要试图直接访问组件;你会后悔的。 JSF的验证机制在防止垃圾进入模型方面效果最佳。

您可以使用不同类型的托管bean;形式的东西:

/*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; 
    } 
    } 
} 

这是使用方法绑定机制的束缚:

<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> 

在未来,你应该能够做到使用Bean验证(JSR 303)这样的事情。

+0

似乎有点难看,但没关系 – razenha 2009-09-29 19:21:42

+0

JSF验证在外地工作,而不是页面(JSF 2 + JSR 303旨在改变的东西)。虽然,这个bean可能会有所改进。另一种选择是自定义渲染器和/或组件,但这对于这样的事情可能太多了。 – McDowell 2009-09-30 10:04:24

2

您可以随时从上下文映射中抽取其他字段的值,并在多个字段上执行验证。类似下面:

public void validatePassword2(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException{ 
    String fieldVal = (String)object; 

    String password1 = (String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("password1"); 
    if(!password1.equalsIgnoreCase(fieldVal)){ 
     FacesMessage message = new FacesMessage("Passwords must match"); 
     throw new ValidatorException(message); 
    } 
} 

和JSF看起来是这样的:

<h:inputSecret value="#{profile.password2}" validator="#{brokerVal.validatePassword2}" required="true" requiredMessage="*required" id="password2" /> 

HTH

+0

这不工作vor我:(我有一个Bean与Bean.password和bean.password2,但如果我验证password2,并尝试获取密码值,我得到空 – Markus 2010-10-19 15:58:08