如何在组件依赖于布尔值的情况下切换验证器。
我有一个selectBooleanCheckbox,当它真的我想要使用FirstValidator时,我想要使用SecondValidator。我没有发现这个"特别"案件。
仅限示例代码:
XHTML:可
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h:selectBooleanCheckbox value="#{testBean.firstValidator}"/>
<h:inputText>
<f:validator validatorId="FirstValidator" />
</h:inputText>
<h:commandButton value="Test" />
<h:messages />
</h:form>
</h:body>
</html>
豆:
@ManagedBean
@ViewScoped
public class TestBean implements Serializable{
private boolean firstValidator;
public boolean isfirstValidator() {
return firstValidator;
}
public void setfirstValidator(boolean firstValidator) {
this.firstValidator = firstValidator;
}
}
Validator1:
@FacesValidator("FirstValidator")
public class FirstValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String valueAsString = (String) value;
if(valueAsString.contains("a")){
throw new ValidatorException(new FacesMessage("Fail!"));
}
}
}
Validator2:
@FacesValidator("SecondValidator")
public class SecondValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
String valueAsString = (String) value;
if(valueAsString.contains("b")){
throw new ValidatorException(new FacesMessage("Fail2!"));
}
}
}
答案 0 :(得分:4)
根据复选框的值设置/禁用验证器。您只需确保在视图构建时(在还原视图阶段运行期间)选择可用的值作为可用值。因此,您绝对不能使用模型值#{testBean.firstValidator}
(仅在更新模型值阶段设置)。您需要确定HTTP请求参数。如果未选中复选框,则为空,否则为空。
首先通过binding
属性将复选框组件绑定到视图(而不是bean!):
<h:selectBooleanCheckbox binding="#{checkbox}" ... />
这样,请求参数可以动态获取为#{param[checkbox.clientId]}
。
现在您可以使用 验证器ID的条件设置:
<f:validator validatorId="#{empty param[checkbox.clientId] ? 'firstValidator' : 'secondValidator'}" />
或条件设置验证程序的disabled
属性:
<f:validator validatorId="firstValidator" disabled="#{not empty param[checkbox.clientId]}" />
<f:validator validatorId="secondValidator" disabled="#{empty param[checkbox.clientId]}" />
请注意,我根据Java实例变量命名约定更改了验证器ID。你在普通的Java代码中也没有这样做,对吗?
Validator FirstValidator = new FirstValidator();