Javascript – Client side validation using javascript with JSF

javascriptjsfjsf-2

I'm using JSF 2.0 and PrimeFaces library. I have a page with several inputs (among them there are 2 p:calendar components).
I want to validate that the second date is not before the first date, but I want this validation to happen in the client, and if validation fails, then don't submit the form and display the h:message that belong to the calendars.
PrimeFaces' calendar has a minDate attribute, but this just works not allowing to choose a previous date using the graphical calendar, but you can still type a previous date and validation passes; so I have to use javascript too.
I can add a "onclick" event to the commandButon to call js function that performs validation, but how can I stop JSF from submitting the form is javascript validation failed? and how can I display the h:message components? I want to avoid going to the server.
Thanks!

This is the code of the calendars:

<p:calendar id="dateFrom" value="#{reqAbsences.dateFrom}" 
            navigator="true" showOn="button" 
            required="true" pattern="dd/MM/yyyy" 
            onSelectUpdate="dateTo dateFromVal hourInput timeFrom timeTo"
            selectListener="#{reqAbsences.handleDateFromSelect}"
            mindate="#{reqAbsences.today}" >
                  <f:validator validatorId="DateValidator"/>
</p:calendar>
<p:message id="dateFromVal" for="dateFrom" showSummary="false"/>
<h:outputLabel value="#{text['global.toDate']}"/>
<p:calendar id="dateTo" value="#{reqAbsences.dateTo}" 
            navigator="true" showOn="button"
            onSelectUpdate="dateToVal"
            selectListener="#{reqAbsences.handleDateToSelect}"
            pattern="dd/MM/yyyy" required="true" mindate="#{reqAbsences.dateFrom}">
                   <f:validator validatorId="DateValidator"/>
</p:calendar>
<p:message id="dateToVal" for="dateTo" showSummary="false"/>

Best Answer

Simply, Your JavaScript method must return true when the validation succeeds. else it has to return false.

function compareDates()
{
  var validDates=true; 
   /*Write your logic to compare your dates
      */
if(validDates) return true;
else return false;
}

when it returns false your form wont be submitted to server.