提交表格甚至A4j验证失败+ jsf

时间:2009-04-15 11:21:34

标签: jsf

我正在使用a4j检查用户名是否存在onblur事件    当用户已存在时,它会显示错误消息,但如果我单击,则显示错误消息    显示提交的错误消息后提交按钮    当涉及到inputtext的required = true时,它不会被提交

                                             required =“true”validator =“#{RegistrationBean.checkFirstName}”>                                              
                                           

public void checkFirstName(FacesContext facesContext,UIComponent component,Object value)
      {

    String name = (String) value;

     if(name.trim().length()==0){
         System.out.println("Name *******");

         String message = bundle.getString("Name_Required");
        FacesContext.getCurrentInstance().addMessage("Reg:firstName",
                new FacesMessage(FacesMessage.SEVERITY_ERROR, message,message));                


     }                  
     if(name.trim().equalsIgnoreCase("tom")){

         String message = bundle.getString("Name_exists");
        FacesContext.getCurrentInstance().addMessage("Reg:firstName",
                new FacesMessage(FacesMessage.SEVERITY_ERROR, message,message));                

    }

  }

任何人都可以建议我出错的地方

1 个答案:

答案 0 :(得分:3)

使用JSF代码,可以更轻松地为您提供帮助。所以我建议你在JSF页面中有类似的东西:

<h:inputText id="firstName" ... validator="#{aBean.checkFirstName}">

Java代码的问题在于,在发生错误时不会抛出任何ValidatorException。因此,您的代码必须是:

public void checkFirstName(FacesContext facesContext, UIComponent component, Object value) {
    String name = (String) value;
    if ((name == null) || name.trim().length() == 0) {
        System.out.println("Name *******");
        String message = bundle.getString("Name_Required");
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message)); // Throw the required error
    }
    if (name.trim().equalsIgnoreCase("tom")) {
        String message = bundle.getString("Name_exists");
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message)); // Throw the already exist error
    }
}

这样,如果此字段中填写的值为空或已存在,将抛出ValidatorException,用户将收到错误消息(不要忘记添加<h:messages/><h:message/>表单中的组件),表单将不会提交!