【问题标题】:jsf view not validating ajax blurjsf视图不验证ajax模糊
【发布时间】:2014-07-17 02:11:03
【问题描述】:

我有一个 ajax 事件模糊来验证数据库中是否已经存在电子邮件并且它可以工作。

<h:outputText value="Email:" />
<p:inputText id="email" value="#{pessoaBean.pessoa.email}"  
    required="true" requiredMessage="Informar o email."
    validatorMessage="Formato de email inválido" >
    <p:ajax event="blur"  listener="#{pessoaBean.verificaEmail}" 
        update="mensagens" />
    <f:validateRegex
        pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
</p:inputText>

豆方法:

public void verificaEmail() {

    if (new PessoaDao().verificaEmail(pessoa) == true) {
        FacesContext.getCurrentInstance().addMessage("formCadastrar:email",
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
                "email already exist"));

    }

}

当我使用命令按钮提交表单时,它会通过我的 ajax 验证并提交我的表单,即使它的错误消息显示在屏幕上。

我的按钮代码:

<p:commandButton value="Cadastrar"
    actionListener="#{pessoaBean.cadastrar}"
    update=":formPrincipal:tabelaPessoas,formCadastrar"
    oncomplete="if (!args.validationFailed){PF('dialogCadastrar').hide();} " 
    />

这里发生了什么?

【问题讨论】:

    标签: ajax jsf-2 primefaces


    【解决方案1】:

    不要在侦听器方法中进行验证工作,因为 JSF 有相应的验证器。据官方docs

    单个验证器应检查它们传递的值和组件,并抛出包含 FacesMessage 的 ValidatorException,记录任何失败以符合所需规则。

    那么让我们来实现你需要的那个吧:

    @FacesValidator("emailValidator")
    public class EmailValidator implements Validator{
    
        @Override
        public void validate(FacesContext context, UIComponent component,
                Object value) throws ValidatorException {
    
                    if (new PessoaDao().verificaEmail(value.toString()) == true) {
                        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
                                "email already exist"));
                    }
    
            }
    
        }
    }
    

    然后,您只需要将验证器附加到您感兴趣的输入:

    <p:inputText id="email" value="#{pessoaBean.pessoa.email}"  
        required="true" requiredMessage="Informar o email."
        validatorMessage="Formato de email inválido" validator="emailValidator" />
    

    这当然可以改进,您可以将正则表达式验证添加到代码本身中,还可以实现自己的电子邮件输入复合组件以重复使用,其中已包含验证器。

    另请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      相关资源
      最近更新 更多