6

我参考了 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

提前致谢

4

1 回答 1

8

将它们标记为无效UIInput#setValid(),通过false

input1.setValid(false);
input2.setValid(false);
input3.setValid(false);

边框特定于 PrimeFaces <p:inputText>,因此您不需要按照其他回答者的建议添加任何 CSS 样板。

Note that this can also be achieved by OmniFaces <o:validateAll> tag without the need to homegrow a custom validator.

于 2013-01-17T15:34:48.473 回答