如何在自定义多字段验证器中标记其他组件无效

时间:2013-01-17 10:23:25

标签: validation jsf jsf-2 primefaces

我指的是BalusC的答案之一: JSF doesn't support cross-field validation, is there a workaround?

我按照同样的方式,并提出如下代码:

在.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 class:

@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);
    }

    }
}

代码工作正常,但我遇到了问题。如何在验证失败时用JSF突出显示name1 inputText(或者name1和name2 inputText)的边框。

图片作为参考: http://img443.imageshack.us/img443/8106/errork.jpg

提前致谢

1 个答案:

答案 0 :(得分:5)

通过falseinput1.setValid(false); input2.setValid(false); input3.setValid(false); 标记为无效。

<p:inputText>

边框特定于PrimeFaces {{1}},因此您无需按照其他回答者的建议添加任何CSS样板文件。

请注意,这也可以通过UIInput#setValid()实现,而无需自定义验证器。