至少填充一个字段时,根据需要验证一组字段 [英] Validate a group of fields as required when at least one of them is filled

查看:58
本文介绍了至少填充一个字段时,根据需要验证一组字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基本注册屏幕(带有按钮注册记录屏幕)中,有两个面板:

In a basic registration screen (with button register records the screen) there are two panels:

数据面板:

地址面板:

我只能通过完成数据"面板进行注册.不必填写地址"面板.但是,如果填写了地址"面板中的至少一个字段,则应要求同一面板中的所有其他字段.

I can register by completing only the Data panel. It is not necessary to fill the Address panel. However, if at least one field of the Address panel is filled, then all other fields in the same panel should be required.

我该如何实现?

推荐答案

如果其他输入提交了非空值,则需要签入required属性.由于这可能会导致很多样板,因此,这里有一个仅包含3个输入组件的启动示例.

You need to check in the required attribute if the other inputs have submitted a non-empty value. Since this can result in quite some boilerplate, here's a kickoff example with only 3 input components.

<h:form id="form">
    <h:inputText id="input1" value="#{bean.input1}" required="#{empty param['form:input2'] and empty param['form:input3']}" />
    <h:inputText id="input2" value="#{bean.input2}" required="#{empty param['form:input1'] and empty param['form:input3']}" />
    <h:inputText id="input3" value="#{bean.input3}" required="#{empty param['form:input1'] and empty param['form:input2']}" />
</h:form>

另一种方法是将组件绑定到视图并使用

An alternative is to bind the components to the view and use UIInput#getValue() to check the value of the previous components and UIInput#getSubmittedValue() to check them for next components (components are namely processed in the order as they appear in the component tree). This way you don't need to hardcode client ID's. You only need to ensure that binding names doesn't conflict with existing managed bean names.

<h:inputText binding="#{input1}" value="#{bean.input1}" required="#{empty input2.submittedValue and empty input3.submittedValue}" />
<h:inputText binding="#{input2}" value="#{bean.input2}" required="#{empty input1.value and empty input3.submittedValue}" />
<h:inputText binding="#{input3}" value="#{bean.input3}" required="#{empty input1.value and empty input2.value}" />

您将了解,当您拥有越来越多的组件时,这会产生难看的样板. JSF实用程序库 OmniFaces 具有 <o:validateAllOrNone> 验证器.另请参见实时演示.根据您的问题标签,您正在使用OmniFaces,因此应该已经设置好了:

You'll understand that this produces ugly boilerplate when you have more and more components. The JSF utility library OmniFaces has a <o:validateAllOrNone> validator for the exact purpose. See also the live demo. Based on your quesiton tags, you're using OmniFaces, so you should already be set with just this:

<o:validateAllOrNone components="input1 input2 input3" />
<h:inputText id="input1" value="#{bean.input1}" />
<h:inputText id="input2" value="#{bean.input2}" />
<h:inputText id="input3" value="#{bean.input3}" />

这篇关于至少填充一个字段时,根据需要验证一组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆