如何验证是否输入了多个输入字段中的至少一个? [英] How to validate if at least one of multiple input fields is entered?
问题描述
我有一个包含3个字段的表单,然后提交按钮.单击按钮时,如果在3个字段中均未输入任何内容,则抛出验证消息.如果输入了3个字段中的任何一个,则将处理数据并使用数据表在同一页面中显示结果.我可以为一个字段抛出验证消息,但不能为两个或更多字段抛出验证消息.这是我的代码.同样,如果我需要传递一个长值,并验证我该怎么做,因为长值不能被验证为isEmpty()
或isNull()
.
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" />
推荐答案
只需让每个字段的required
属性检查其他字段的提交值是否存在.提交的值可在客户端客户ID作为键的参数映射#{param}
中获得.
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.
这是一个开球示例:
<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.
或者,您可以使用 OmniFaces
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>
请注意,以动作方法执行验证是错误的设计.为此,您应该使用标准的JSF验证工具,例如requiered
,validator
,<f:validator>
和/或<f:validateXxx>
.
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>
.
这篇关于如何验证是否输入了多个输入字段中的至少一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!