开发者

Client side validation using javascript with JSF

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"
            onSelectUpdat开发者_JAVA技巧e="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"/>


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.


Say we have an HTMLFormElement with id "formId", i.e: <form id="formId">...</form>

The formal way to use JavaScript & DOM to stop an event is to call the event object's "preventDefault" method (or set its returnValue property to false, depending on the browser).

Example:

function checkSubmit(e) { var ev = e || window.event;

if (needs to cancel submit) {
    if (ev.preventDefault) {
        ev.preventDefault();
    }
    ev.returnValue = false;
    return false;
}

} /* Allocating the above function as an event handler of the submit event of the above form element */ document.getElementById('formId').addEventListener('submit', checkSubmit, false);

Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜