【问题标题】:JSF one error message for two required input fields两个必需输入字段的 JSF 一条错误消息
【发布时间】:2012-09-28 13:11:35
【问题描述】:

我正在尝试为两个必填字段只显示一个。 目前,如果两个字段都为空,则会出现两条错误消息。如果两个或一个字段都为空,我想实现只有一条消息。

代码如下:

<x:inputText
    value="#{bean.proxyUrl}"
    id="idProxyUrl"
    required="true"
    />
<x:outputText value=":" />
<x:inputText
    value="#{bean.proxyPort}"
    id="idProxyPort"
    required="true"
    />
<x:message for="idProxyUrl" errorClass="errorMessage" style="margin-left: 10px;" />
<x:message for="idProxyPort" errorClass="errorMessage" style="margin-left: 10px;" />

我能做些什么,无论一个或两个字段是否为空,我都只会收到一条消息。

【问题讨论】:

  • x: 前缀无法识别为任何已知的 JSF 组件库。我可以假设它是使用 URI http://java.sun.com/jsf/html 设置的标准 JSF HTML 组件吗? (如果是这样,您为什么要更改世界上每个人都在使用的标准 h: 前缀?)
  • 这可能会对您有所帮助...stackoverflow.com/q/10007438/617373
  • x: 指向http://myfaces.apache.org/tomahawk

标签: java jsf


【解决方案1】:

您可以为第二个组件指定一个特殊的验证器来检查第一个组件的 SubmittedValue。我为检查相应的确认密码字段的 PasswordValidator 做了类似的事情。

@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator {    

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) throws ValidatorException {


        String password = (String) value;


        UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm");
        String confirm = (String) confirmComponent.getSubmittedValue();

        if (password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please confirm password", null);
            throw new ValidatorException(msg);
        }


        if (!password.equals(confirm)) {
            confirmComponent.setValid(false); 
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The entered passwords do not match", null);
            throw new ValidatorException(msg);
        }


    }

您必须检查其他组件的提交值的原因是在生命周期的流程验证阶段调用验证器。在此阶段完成并且每个提交的值都通过验证之前,不会应用任何提交的值。

【讨论】:

  • 谢谢。有一些小的变化,因为这些领域不必相等,这就是有帮助的。我对 JSF 很陌生,需要学习很多东西!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2011-02-03
  • 1970-01-01
  • 2013-10-02
相关资源
最近更新 更多