繁体   English   中英

需要交互/验证的表单中的复合组件

[英]Composite-Component within a form that requires interaction/validation

快速背景:我已经在我的网站上使用primefaces自定义组件放置了一个验证码。 负责人不喜欢它,因为它太难使用并且客户在抱怨。 我决定要创建一个简单的组件(即:4 + 9 =并由用户输入答案)以避免产生一些垃圾邮件。 无需使用图像就可以显示问题,只需使用简单的文本即可。 这使我开始研究自定义组件和复合组件(来自本文本文 )。

现在,问题不仅仅在于临时的基本“验证码样式验证”。 它更多地是关于复合组件和支持bean组合的。

我要做的就是创建这种样式的支持bean:

<cc:interface>

    <cc:attribute name="label" />
<!-- edited -->
    <cc:attribute name="required" />
<cc:attribute name="ident" />

</cc:interface>


<cc:implementation>

    <h:panelGrid columns="3">
        <h:outputText value="#{captcha.text}"/>
        <h:inputText id="#{cc.attrs.ident}" value="#{captcha.entered}" validator="#{captcha.validate}" required="#{cc.attrs.required eq 'true'}" label="#{cc.attrs.label}" />
        <h:message for="captchaAnswer" />
    </h:panelGrid>

    <h:inputHidden value="#{captcha.value}" />

</cc:implementation>

然后,我想以这种方式使用此组件:

<h:form>
    ...
    <tr>
        <td>
            <my:captcha label="Captcha" ident="captcha" required="true"/> <!-- added after suggested comment -->
            <br/>
            <h:message for="captcha" class="error"/>
        </td>
    </tr>
    <tr>
        <td colspan="3" class="center">
            <h:commandButton class="button" value="#{msg['contact.label.send']}" action="#{contact.send}" >
        </h:commandButton>
        </td>
    </tr>
    ...
</h:form>

如何确保在提交时可以检查我的{#captcha.entered}值是否为必需值,如果没有,则在表单上返回验证消息并阻止其提交?

captcha支持Bean很简单,并具有以下值: textanswer和, entered还有一个简单的函数来检查是否answer == entered

编辑:(尝试#1)自定义验证器将如下所示

public void validate(FacesContext context, UIComponent toValidate, Object value) {

    System.out.println("validating");

    String input = (String) value;

    //check to see if input is an integer
    //if not we know right away that the value is not good
    if(StringUtils.isNumeric(input)) {
        //if the input is numeric, convert to an integer
        int intValue = new Integer(input).intValue();
        if (intValue != answer) {
            ((UIInput) toValidate).setValid(false);

            FacesMessage message = new FacesMessage("Not a match!!");
            context.addMessage(toValidate.getClientId(context), message);
        }
    }
}

在这种情况下,验证器甚至不会被调用,并且我也不会收到错误消息。

编辑#2

经过一些工作和评论提示,我开始工作了。 为了使h:message工作,我需要添加属性ident而不是id 如果没有,我必须这样引用它: <h:message for="captcha:captcha" />这不是理想的结果。

这个问题的主要问题是我找不到参考。

通过添加属性ident而不是id我可以使用它。 请参考相关的修改#2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM