Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation failed javascript callback in JSF

Tags:

jsf

primefaces

I have a template in which I can add a CSS error class to a div when the validation of a component has failed and it renders a pretty nice effect on the browser.

Now, I don't need to add a css class to a component (this won't help me), but rather I need to change the css of the html that surrounds it, this is pretty simple with jQuery, however I can't seem to find a javascript callback for failed validation, is this possible? I'm also using primefaces (in case they provide such capabilities).

Markup:

<div class="control-group ERROR_CLASS_GOES_HERE_IF_VALIDATION_FAILED">
   <label class="control-label">Input value:</label>
   <div class="controls">
      <h:inputText class=" inputbox" type="text" required="true" /> <!--Component that can fail -->
   </div>
</div>

if the input text is empty, I need the div that wraps the "control group" to have an extra class. I can turn it into a <h:panelGroup> so it is a JSF component but still I wouldn't know how to do it. Javascript seems easier as I can do a:

jQuery("#ID_OF_DIV").addClass("error_class") 
like image 896
arg20 Avatar asked Mar 11 '13 22:03

arg20


2 Answers

Just let JSF/EL conditionally print the class based on FacesContext#isValidationFailed().

<div class="control-group #{facesContext.validationFailed ? 'error_class' : ''}">

You only need to ensure that this element is covered by ajax update/render.

Another way would be hooking on the oncomplete event of an arbitrary PrimeFaces ajax based component. There's an args object available in the scope which in turn has a validationFailed property. E.g. <p:commandButton oncomplete> or even <p:ajaxStatus oncomplete>.

<p:ajaxStatus ... oncomplete="if (args &amp;&amp; args.validationFailed) $('#ID_OF_DIV').addClass('error_class')">
like image 121
BalusC Avatar answered Oct 24 '22 17:10

BalusC


If you want to do everything on the client side.

     <h:outputText class="samplecls" rendered="#{facesContext.validationFailed}"
              value="Please enter all the required fields">
    </h:outputText>  


    <div class="control-group ERROR_CLASS_GOES_HERE_IF_VALIDATION_FAILED">
       <label class="control-label">Input value:</label>
       <div class="controls">
          <h:inputText class=" inputbox" type="text" required="true" /> <!--Component that can fail -->
       </div>
    </div>

Javascript/Jquery

 This class will exist in DOM only validation fails by rendered="#{facesContext.validationFailed}"


  $(window).load(function(){ 
      if($('.samplecls').length>0){
            $("#ID_OF_DIV").addClass("error_class");    
        }
});
like image 27
SRy Avatar answered Oct 24 '22 17:10

SRy