How to validate if at least one of multiple input fields is entered?

后端 未结 2 1462
遇见更好的自我
遇见更好的自我 2020-12-07 03:05

I have a form with 3 fields, and submit button. when button clicked, if none is entered in 3 fields, throw validation message. If any one of the 3 fields are entered process

相关标签:
2条回答
  • 2020-12-07 03:46

    At least for iceFaces another approach to validate across multiple fields, especially when the validation is more complex than just "required", is to use application level validation inside your backing bean.

    @see Custom Validator in Backing Beans

    • Add the validator attribute to you rcomponent and point it to teh validation method in your backing bean
    • inside teh backing bean you can now access all form fields and do cross validation

    Regards

    Rob

    0 讨论(0)
  • 2020-12-07 03:50

    Just let the required attribute of each field check the presence of the submitted value of the other fields. The submitted value is available in the parameter map #{param} by the client ID as key.

    Here's a kickoff example:

    <h:form id="form">
        <h:inputText id="field1" ... required="#{empty param['form:field2'] and empty param['form:field3']}" />
        <h:inputText id="field2" ... required="#{empty param['form:field1'] and empty param['form:field3']}" />
        <h:inputText id="field3" ... required="#{empty param['form:field1'] and empty param['form:field2']}" />
    </h:form>
    

    It gets only more ugly as the amount of fields grows.

    Alternatively, you can use OmniFaces <o:validateOneOrMore>:

    <h:form id="form">
        <h:inputText id="field1" ... />
        <h:inputText id="field2" ... />
        <h:inputText id="field3" ... />
    
        <o:validateOneOrMore id="oneOrMore" components="field1 field2 field3" />
        <h:message for="oneOrMore" />
    </h:form>
    

    Please note that performing validation in action method is bad design. You should use the standard JSF validation facilities for this such as requiered, validator, <f:validator> and/or <f:validateXxx>.

    0 讨论(0)
提交回复
热议问题