Wednesday, September 26, 2012

By Passing JSF Form Validation

Consider this situation where you have a JSF form with two buttons; a 'Cancel' button and a 'Submit' button.   You also want to add validation components to the form so that certain fields are required.

Using JSF and Richfaces, it is very trivial thing to do, you can add required="true" to the respective input form components.  But what can you do if want validations to happen only when you click the 'Submit' button?  

Thanks to Prasun's blog, bypassing validation for 'Cancel' button can be done in a very easy way.  All you have to do is the following :

<h:inputText value="..." 
required="#{empty param['form:cancelButId']}" requiredMessage=".." >

And you have to put id of the buttons to :

<h:commandButton value="Cancel" id="cancelButId" action="..." />
 The reason behind doing so is that when a JSF form is submit, it takes the IDs of all the components and send the request.  If you click 'Cancel' button, the request will contain the ID of the Cancel button as a parameter.  Therefore, the condition in the required tag will return false and the input text value is not required.
 
Initially, I was not able to achieve the desired output.  After doing a little bit of research, I realized that my command buttons are rendered slightly differently, as I put an image on the button like the following:
<h:commandButton action="..." src="link to image" />

It causes the command button to be rendered as type = "image" instead of type="button" or type="submit".  When I removed the src field, it works as it should.  So, to put an image back on to the button, I used the image attribute of the h:commandButton