在显示需要值的消息之前执行javascript函数

时间:2011-06-15 15:12:00

标签: javascript jquery jsf captcha

我有一个一直困扰最近几个小时的简短问题:

如何在显示需要值的消息之前执行javascript函数?(在表单提交时,如果需要进行entere,则在其中提交一些值为空。)

我在jsp页面中为jQuery使用RealPerson captcha插件时遇到了这个问题。当我点击提交按钮,输入字段为验证码为空时,验证码就会消失。

更新1:

我试过绑定并渲染但问题似乎仍然存在。

<h:outputLabel for="captcha" value="#{ui.pleaseEnterTextInTheImage}"  rendered="#{sessionBean.showCaptcha}"/>
<h:panelGroup rendered="#{sessionBean.showCaptcha}">
     <h:inputText id="captcha" styleClass="captcha" binding="#{captcha}"
                                                     validator="#{validationBean.captchaValidator}" required="true"/>
     <h:outputText value=" "/><h:message for="captcha" styleClass="captchaMsg"/>
</h:panelGroup>
<h:panelGroup rendered="#{!captcha.valid}">
     <script>alert('Foo input is invalid!');</script>
</h:panelGroup>

更新2:

当页面上线时:

before

点击“注册”后,验证码条目留空: after

更新3:

我使用的jQuery代码。

首先在页面加载中,我将验证码分配给字段:

$(function() {
      $('.captcha').realperson();
});

然后,在通过从我的bean调用此函数重新呈现字段后重新分配新的验证码之后:

function updateCaptchaFromBean() {
    $(function() {
        $('.captcha').realperson();
    });
}

找到解决方案

我找到了一个简单的javascript技巧,用onclick()来解决这个问题:

<h:commandButton styleClass="buttonSubmit" value="#{ui.registerBUTTON}"
     action="#{register.addAction}"
     onclick="if ($('.captcha').val() == '') return false"
     id="submitBtn" />

1 个答案:

答案 0 :(得分:1)

假设JSF 1.x在没有ajax功能的JSP上,以下是最简单的方法:

<h:panelGroup rendered="#{!foo.valid}">
    <script>alert('Foo input is invalid!');</script>
</h:panelGroup>
...
<h:inputText id="foo" binding="#{foo}" value="#{bean.foo}" required="true" />
<h:message id="fooMessage" for="foo" />

根据评论

更新,它不起作用。根据您更新的问题,您似乎使用自定义验证器。此问题只能意味着您没有在自定义输入验证程序中抛出ValidatorException,而只是添加了一条消息。这是错的。您应该抛出ValidatorException,以便JSF可以将组件标记为无效。

因此,您不应该在验证器方法中执行以下操作:

context.addMessage(component.getClientId(context), new FacesMessage("Fail"));

但你应该做

throw new ValidatorException(new FacesMessage("Fail"));

这样#{!captcha.valid}将解析为true