简体   繁体   中英

JSF two required h:inputText (exclusive or)

I would that 2 imputText are required: if email is valued, the mobilephone is not required and vice versa. How can I do?

Thanks.

                <h:inputText required="true" id="usEmail" size="20"
                    value="#{rwUser.usEmail}" />

                <h:message for="usEmail" style="color:red" />


                    <h:outputText value="#{msg.mobilephone}" styleClass="textMessage" />

                <h:inputText id="usMobilephone" size="20"
                    value="#{rwUser.usMobilephone}" />

                <h:message for="usMobilephone" style="color:red" />

Several ways.

  • Bind the UIInput components to the view and in the required attribute of the first, check the submitted value of the second and in the required attribute of the second, check the value of the first (components are namely processed in the order as they appear in the view).

     <h:inputText binding="#{usEmail}" ... required="#{empty usMobilePhone.submittedValue}" /> <h:inputText binding="#{usMobilePhone}" ... required="#{empty usEmail.value}" /> 
  • Check the presence of the submitted value in the request parameter map.

     <h:inputText binding="#{usEmail}" ... required="#{empty param[usMobilePhone.clientId]}" /> <h:inputText binding="#{usMobilePhone}" ... required="#{empty param[usEmail.clientId]}" /> 

    Or with hardcoded client IDs:

     <h:form id="form"> <h:inputText id="usEmail" ... required="#{empty param['form:usMobilePhone']}" /> <h:inputText id="usMobilePhone" ... required="#{empty param['form:usEmail']}" /> 
  • Use OmniFaces <o:validateOneOrMore> .

     <h:inputText id="usEmail" ... /> <h:inputText id="usMobilePhone" ... /> <o:validateOneOrMore components="usEmail usMobilePhone" showMessageFor="@all" /> 

I think the <o:validateOneOrMore> of the OmniFaces is what you need. See also the <o:validateOneOrMore> showcase .

You can also use binding to get a reference from one component to another:

<h:inputText required="true" id="usEmail" binding="usEmail" 
    size="20" value="#{rwUser.usEmail}" required="#{empty usMobilePhone.value}" />    

<h:inputText id="usMobilephone" size="20" value="#{rwUser.usMobilephone}" 
    binding="usMobilePhone" required="#{empty usEmail.value}"/>

Note that usEmail.value refers to the UIComponent object corresponding to the inputText, not the managed bean value.

If that doesn't work you may need to replace value with submittedValue because of the JSF lifecycle - UIComponent.value doesn't get set until after validations succeed, and submittedValue is what actually got posted with the form submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM