使用转换器跨所需字段验证消息

时间:2017-09-11 15:31:23

标签: validation jsf primefaces bean-validation

我有一个包含多个字段的表单,其中我需要其中一个字段需要继续或一组字段。为简单起见,我只需在此处粘贴一个更简单的代码版本

    <h:form id="searchForm">
        <p:growl for="searchForm" showDetail="true" showSummary="true"/>
        <p:inputText id="name"
            value="#{backingBean.name}"
            required="#{backingBean.nameRequired and backingBean.masterRequired}">
            <p:ajax />
        </p:inputText>
        <h:panelGroup id="dateForm">
            <p:inputMask id="date"
                value="#{backingBean.date}"
                mask="99/99/9999"
                required="#{backingBean.dateRequired and backingBean.masterRequired}"
                converterMessage="Please insert using format dd/mm/yyyy">
                <f:convertDateTime pattern="dd/MM/yyyy" />
                <f:validator validatorId="dateValidator" />
                <p:ajax update="dateForm" />
            </p:inputMask>
        </h:panelGroup>
        <p:selectOneMenu id="documentType" effect="fade"
            value="#{backingBean.documentType}"
            required="#{backingBean.documentRequired and backingBean.masterRequired}">
            <f:selectItem itemLabel="Select document type" noSelectOption="true" />
            <f:selectItems
                value="#{constantsController.docType.entrySet()}"
                var="entry" itemValue="#{entry.key}" itemLabel="#{entry.value}" />
            <p:ajax />
        </p:selectOneMenu>

        <p:inputText id="documentNumber"
            value="#{backingBean.documentNumber}"
            required="#{backingBean.documentRequired and backingBean.masterRequired}">
            <p:ajax />
        </p:inputText>

        <p:commandButton id="searchButton"
            value="Search"
            action="#{controllerBean.submitSearch}"
            icon="ui-icon-search">
            <p:ajax
                listener="#{backingBean.checkRequired()}" update="@form" />
        </p:commandButton>

    </h:form>

当所有字段都为空时,会显示它应该显示的字段。现在我需要的是inputMask日期,只显示转换器消息和验证消息。当需要显示requiredMessage时,我需要它不显示消息。

我尝试放置<p:message for="date" rendered="#{!empty param['date']}" />但它不起作用,因为它没有在第一次加载时呈现,而ajax没有更新panelGroup,我认为这是因为我给转换器一个无效值,它不会触发更新。

其他信息:

如您所见,我有多个必填字段,我至少需要其中一个字段:

-name

-date

- 文档类型+文档编号

现在,为了验证必填字段,我在我的支持bean上执行以下操作:

public void checkRequired() {

    nameRequired = name.equals("");
    dateRequired = date == null;
    documentRequired = documentType.equals("") || documentNumber.equals("");

    masterRequired = nameRequired && dateRequired && documentRequired;
    if(masterRequired)
    {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Incomplete form",
                "Please insert at least 1 field");
        FacesContext.getCurrentInstance().addMessage("searchForm", message);
        return;
    }
}

0 个答案:

没有答案