【问题标题】:Jsf validation with composite component is not working properly使用复合组件的 Jsf 验证无法正常工作
【发布时间】:2012-09-08 08:19:28
【问题描述】:

我的英语不好,很抱歉。我的问题是关于 jsf 验证。当我的验证 bean 抛出 ValidatorException 时,我的托管 bean save_method 有效。但我不希望我的 save_method 有效。如果电子邮件无效,我的 save_method不应该工作。

复合接口

<composite:attribute name="validator" required="false"
        method-signature="void Action(javax.faces.context.FacesContext, javax.faces.component.UIComponent,Object)" />

这样的复合实现

<c:if test="#{cc.getValueExpression('validator')!=null}">
<p:inputText value="#{cc.attrs.value}" id="#{cc.attrs.id}"
required="#{cc.attrs.required}" validator="#{cc.attrs.validator}"/>

验证 bean 中的验证方法。

@Override
public void validate(FacesContext context, UIComponent component, Object value) throws    ValidatorException {
String email = (String) value;
Pattern mask = null;
mask = Pattern.compile(EMAIL_REGEX);
Matcher matcher = mask.matcher(email);

if (!matcher.matches()) {
    messageManager.warn(MessageManager.Bundles.WO, "validator.message.email");

   throw new ValidatorException(new FacesMessage("hoppala"));
}
}

还有我的托管 bean 保存方法。

 @Override
    public boolean save() {
       super.save();
}

【问题讨论】:

    标签: java validation jsf composite-component


    【解决方案1】:

    您是否在使用低于 2.1.10 版本的 mojarra?最近修复了was a bug。因此,如果可以,请更新到最新的 2.1.13。但无论如何,在 JSF 中,您不会按照您描述的方式进行操作。我建议使用&lt;f:validator/&gt; 来应用验证器,如下所示:

    <mytags:customInput value="#{validationModel.value}">
       <f:validator for="input" validatorId="org.validationexample.EmailValidator" />
    </mytags:customInput>
    

    你的复合组件必须实现&lt;cc:editableValueHolder&gt;

    <cc:interface>
        <cc:attribute name="value"/>
        <cc:editableValueHolder name="input" targets="inputText"/>
    </cc:interface>
    
    <cc:implementation>
        <p:inputText id="inputText" value="#{cc.attrs.value}" />
    </cc:implementation>
    

    最后,您的验证由专用的验证器类处理:

    @FacesValidator("org.validationexample.EmailValidator")
    public class EmailValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            // your validation here
        }
    
    }
    

    无论如何,还有其他方法/口味。您也可以将&lt;f:validator&gt; 直接放入&lt;p:inputText&gt; 内的复合组件中。由于&lt;f:validator&gt; 具有disabled 属性,您可以按需禁用它。另一种方法是使用 Bean Validation 并采用 Hibernate Validator 附带的现有 EmailValidator。在这种情况下,您只需在属性上方设置注释 @Email。

    【讨论】:

    • +1 你在这个问题上打败了我。是否也可以使用&lt;composite:renderFacet&gt; 将构面也插入到复合组件中?
    • @maple_shaft 如果您的意思是使用构面选择性地应用验证器 (?) - 不。但也许我理解错了……
    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多