仅当您选择了某些值时,我才会使用a4j
它来呈现 inputText selectOneMenu
:
<h:selectOneMenu value="#{MyBean.selectedValue}">
<f:selectItems value="#{MyBean.listOfValues}" />
<a4j:support event="onchange" reRender="requiredText" ajaxSingle="true"/>
</h:selectOneMenu>
<a4j:outputPanel id="requiredText">
<h:inputText value="#{MyBean.inputValue}" rendered="#{(MyBean.selectedValue == value_1) || (MyBean.selectedValue == value_2) || ...}" />
</a4j:outputPanel>
为了避免 inputText 的rendered
参数上出现大字符串,我建议您创建一个执行以下条件的布尔函数:rendered="#{MyBean.inputTextIsRendered}
.
客户端解决方案
还有一个基于验证器的解决方案。这是我的方法:
上面的selectOneMenu
代码使用binding
标签将在 中选择的值selectOneMenu
与一个属性绑定,该属性将在验证器方法中检索,为inputText
组件声明。
然后,您需要创建CheckInputValue
验证器类。
public class CheckInputValue implements Validator {
public CheckInputValue() {}
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
//We retrieve thei binded value:
UIInput confirmComponent = (UIInput) component.getAttributes().get("selectedValue");
String theValue = confirmComponent.getSubmittedValue();
//Here you check the retrieved value with the list of values that makes your inputText required.
//In these cases you will chech the inputText is not empty and, if so, you return a ValidatorException:
if(isEmpty){
FacesMessage message = new FacesMessage();
message.setDetail("inputText cannot be empty");
message.setSummary("inputText cannot be empty");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
最后,您必须在以下位置声明您的验证器类faces-config.xml
:
<validator>
<validator-id>CheckInputValue</validator-id>
<validator-class>myPackage.myValidations.CheckInputValue</validator-class>
</validator>