How to find indication of a Validation error (required=”true”) while doing ajax command

Not specifically for required="true", but you can check by #{facesContext.validationFailed} if validation has failed in general. If you combine this with checking if the button in question is pressed by #{not empty param[buttonClientId]}, then you can put it together in the rendered attribute of the <h:outputScript> as follows:

<h:commandButton id="add_something_id" binding="#{add}" value="Add" action="#{myBean.addSomething(false)}">
    <f:ajax execute="@form" render="@form someTable" />
</h:commandButton>
<h:outputScript rendered="#{not empty param[add.clientId] and not facesContext.validationFailed}">
    $("#dialog_id").dialog("close");
</h:outputScript>

(note that you need to make sure that the script is also re-rendered by f:ajax)

A bit hacky, but it’s not possible to handle it in the onevent function as the standard JSF implementation doesn’t provide any information about the validation status in the ajax response.

If you happen to use RichFaces, then you could just use EL in the oncomplete attribute of the <a4j:xxx> command button/link. They are namely evaluated on a per-request basis instead of on a per-view basis as in standard JSF and PrimeFaces:

<a4j:commandButton ... oncomplete="if (#{!facesContext.validationFailed}) $('#dialog_id').dialog('close')" />

Or if you happen to use PrimeFaces, then you could take advantage of the fact that PrimeFaces extends the ajax response with an additional args.validationFailed attribute which is injected straight in the JavaScript scope of the oncomplete attribute:

<p:commandButton ... oncomplete="if (args &amp;&amp; !args.validationFailed) $('#dialog_id').dialog('close')" />

(note that &amp; is been used instead of &, because & is a special character in XML/XHTML)

Or you could use the PrimeFaces’ RequestContext API in the bean’s action method to programmatically execute JavaScript in the rendered view.

RequestContext.getCurrentInstance().execute("$('#dialog_id').dialog('close')");

No conditional checks are necessary as the bean’s action method won’t be invoked anyway when the validation has failed.

Leave a Comment