Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deactivating commandButton functionality if inputText validation fails or ajax call starts

I have the following piece of code inside a form:

<p:panel id="panel" header="lalalala">
    <h:panelGrid columns="5">

        <h:outputLabel value="Enter name" for="name" />

        <p:inputText id="name" value="#{userBean.name}"
            required="true" label="name" maxlength="15"
            validatorMessage="oops"
            requiredMessage="ooopps">
            <f:validateRegex
                pattern="^somepattern$">
            </f:validateRegex>
            <p:ajax event="blur" update="inputValidationMessage" />
        </p:inputText>

        <p:message id="inputValidationMessage" showSummary="false"
            for="name" />
        <p:watermark for="name" value="eg. John" />

    </h:panelGrid>

    <p:commandButton id="submitButton" value="Submit" update="panel"
        actionListener="#{userBean.save}"
        onclick="handleOnclick"
        oncomplete="handleAjaxResponse(xhr, status, args)">
    </p:commandButton>
    <p:messages autoUpdate="true" globalOnly="true" showDetail="true" />
</p:panel>

So the validation messages work well on the inputText element. But the submit button is still making an Ajax request when clicked, even though the input is invalid. I want the Ajax request to be sent iff the inputText is valid.

How do I do that?

Furthermore; there is another case I'd like to deactivate the button. This is the case where inputText is validated and the user clicks the button. The reason for this one is, I don't want the user to mistakenly flood requests. (i.e repeatedly press the submit button)

Currently, the handleOnclick javascript function only shows a modal dialog box saying "wait". Since that dialog is modal, the background is inaccessible. However, that still doesn't prevent the user from pressing it repeatedly because 1 second passes between onclick and modal dialog showing. Furthermore; this approach doesn't prevent submitting invalid data. What can you suggest?

I use JSF2.0 and Primefaces 3.0.

Any help appreciated.

like image 975
Murat Derya Özen Avatar asked Jan 16 '12 21:01

Murat Derya Özen


1 Answers

You can use the button's disabled attribute for it. Just set it to true whenever FacesContext#isPostback() returns false (so, it's an initial request), or when it's true (so, a form submit has occurred), then check if FacesContext#isValidationFailed() returns true (so the validation has failed in general).

<p:commandButton ... disabled="#{not facesContext.postback or facesContext.validationFailed}" />

You only need to ensure that you update the button on ajax requests as well, so that it will reappear either enabled or disabled when necessary.

<p:ajax event="blur" update="inputValidationMessage submitButton" />
like image 145
BalusC Avatar answered Nov 06 '22 23:11

BalusC