我参考了 BalusC 的一个答案: JSF 不支持跨字段验证,有解决方法吗?
我遵循相同的方式,并得出如下代码:
在 .xhtml 中
<h:form id="form1">
<div>
<p:messages globalOnly="true" display="text" />
<h:inputHidden value="true">
<f:validator validatorId="fooValidator" />
<f:attribute name="input1" value="#{input1}" />
<f:attribute name="input2" value="#{input2}" />
<f:attribute name="input3" value="#{input3}" />
</h:inputHidden>
<h:panelGrid columns="3">
<h:outputText value="name 1: " />
<p:inputText binding="#{input1}" id="input11" value="#{testPage.input1}" />
<p:message for="input11" display="text"/>
</h:panelGrid>
<h:panelGrid columns="3">
<h:outputText value="name 2: " />
<p:inputText binding="#{input2}" id="input22" value="#{testPage.input2}" />
<p:message for="input22" display="text"/>
</h:panelGrid>
<h:panelGrid columns="3">
<h:outputText value="name 3: " />
<p:inputText binding="#{input3}" id="input33" value="#{testPage.input3}" />
<p:message for="input33" display="text"/>
</h:panelGrid>
<p:commandButton value="Submit" action="#{testPage.submitValidator}" update=":updateBody" />
</div>
</h:form>
java类:
@FacesValidator(value="fooValidator")
public class CustomValidator2 implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
UIInput input1 = (UIInput) component.getAttributes().get("input1");
UIInput input2 = (UIInput) component.getAttributes().get("input2");
UIInput input3 = (UIInput) component.getAttributes().get("input3");
Object value1 = input1.getSubmittedValue();
Object value2 = input2.getSubmittedValue();
Object value3 = input3.getSubmittedValue();
if (value1.toString().isEmpty() && value2.toString().isEmpty() && value3.toString().isEmpty()) {
String errorMsg = "fill in at least 1";
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsg, errorMsg);
FacesContext.getCurrentInstance().addMessage("form1:input11", msg);
//throw new ValidatorException(msg);
}
}
}
代码工作正常,但我面临一个问题。如何在验证失败时用红色突出显示 name1 inputText(或 name1 和 name2 inputText)的边框,这通常由 JSF 完成。
图片作为参考:http: //img443.imageshack.us/img443/8106/errork.jpg
提前致谢