Time for action – validate the UserName using AJAX listeners

Let's add AJAX event listener keyup event to the UserName input field so that as you type, it will check if the username entered is already in use or not.

  1. Create viewAjaxListener.xhtml with registration form to validate the UserName using AJAX Listener as follows:
    <h:form id="registrationForm">
      <p:panel header="Registration Form" style="width: 800px;">
      <h:panelGrid columns="3">
        <p:outputLabel value="UserName:*"/>
        <p:inputText id="userName" value="#{userController.registrationUser.userName}" required="true" label="UserName">
          <p:ajax event="keyup" listener="#{userController.checkUserNamesExists()}" update="userNameMsg"/>
        </p:inputText>
        <p:message id="userNameMsg" for="userName"/>
        
        <p:outputLabel value="Password:*"/>
        <p:password id="password" value="#{userController.registrationUser.password}" required="true" label="Password"/>        
        <p:message id="passwordMsg" for="password"/>
        
        <p:outputLabel value="FirstName:*"/>
        <p:inputText id="firstName" value="#{userController.registrationUser.firstName}" required="true" label="FirstName"/>
        <p:message id="firstNameMsg" for="firstName"/>    
        
        <p:commandButton action="#{userController.register}" value="Register" update="registrationForm"/>    
        
      </h:panelGrid>
      </p:panel>
    </h:form>
  2. Create a UserController.java managed bean with the checkUserNamesExists() method to check whether the entered UserName is already in use or not and add the error message accordingly:
    public void checkUserNamesExists()
    {
      String userName = this.registrationUser.getUserName();
      if("admin".equals(userName) || "test".equals(userName))
      {
        String msg = "UserName ["+userName+"] already in use.";
        FacesContext.getCurrentInstance().addMessage("registrationForm:userName", 
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
      }
    }
  3. Point your browser to http://localhost:8080/chapter01/viewAjaxListener.jsf.

Enter admin or test in the UserName field then you should see the error message displayed immediately as in the following screenshot:

Time for action – validate the UserName using AJAX listeners

What just happened?

We have used AJAX listener in conjunction with keyup event on the UserName input field. So for each keyup event the callback method checkUserNamesExists() will be invoked to check whether the entered UserName value is admin or test, and adds error message if it is. As we are updating the view component with ID userNameMsg using update="userNameMsg", the error message is displayed immediately using the AJAX update.