使用JavaScript和JSF进行客户端验证 [英] Client side validation using javascript with JSF
问题描述
我正在使用JSF 2.0和PrimeFaces库.我有一个包含多个输入的页面(其中有2个p:calendar组件). 我想验证第二个日期不在第一个日期之前,但是我想在客户端进行此验证,如果验证失败,则不要提交表单并显示属于日历的h:message. PrimeFaces的日历具有minDate属性,但这仅允许不允许使用图形日历选择先前的日期,但是您仍然可以键入先前的日期和验证通行证;所以我也必须使用javascript. 我可以在commandButon上添加一个"onclick"事件,以调用执行验证的js函数,但是如何阻止JSF提交表单(JavaScript验证失败)呢?以及如何显示h:message组件?我想避免去服务器. 谢谢!
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!
这是日历的代码:
<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"/>
推荐答案
简单来说,验证成功后,您的JavaScript方法必须返回true.否则它必须返回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;
}
当它返回false时,您的表格将不会被提交到服务器.
when it returns false your form wont be submitted to server.
这篇关于使用JavaScript和JSF进行客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!