Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

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

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 the data and show results back in same page using data table. I am able to throw validation message for one field, but not for 2 fields or more.Here is my code. As well, if I have a long value that I need to pass, and validate how can i do that, since long value can not be validated as isEmpty() or isNull().

Here is my code, I want to use it with multiple fields and with fields that have long values get validated.

<h:inputText id="userName" value="#{user.userName}" required="true"
    requiredMessage="Please enter username" />

<h:inputText id="empId" value="#{user.empId}" required="true"
    requiredMessage="Please enter Employee Id" />

<h:inputText id="acctNm" value="#{user.acctNm}" required="true" 
    requiredMessage="Please enter Employee Id" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...