Validating an email address in PrimeFaces p:inputText field with p:ajax

The example that follows demonstrates how to validate an email address inputted from a PrimeFaces <p:inputText /> field.  It validates the correctness of the email address as well as its existence.  PrimeFaces version 3.4.1 was used to test this demonstration.

Here is the markup that initiates the process:

<h:form prependId="false"> 
    <h:panelGrid id="panel">               
        <h:panelGroup>
            <p:inputText  id="email" value="#{indexBean.emailAddress}" size="30" >
                <p:ajax event="blur" 
                        onstart="$('#progressind').css('visibility','visible');" 
                        oncomplete="$('#progressind').css('visibility','hidden');" 
                        listener="#{indexBean.validateEmail}" 
                        update="messages" />
            </p:inputText>
            <!-- progress indicator -->
            <img id="progressind" src="./images/prog.gif" width="20" 
                 style="margin-left: 10px;border:0px;visibility:hidden"  />
        </h:panelGroup>   

        <p:watermark for="email" value="Enter email address" />
        <p:inputText id="lastname" size="30" />
        <p:commandButton update="messages" value="Submit" 
                         actionListener="#{indexBean.process}" />

        <p:messages id="messages" showDetail="true" showSummary="true" 
                    closable="true" />
    </h:panelGrid>
</h:form>                    

The validation is handled from by <p:ajax /> blur event handler which is listened to by validateEmail bean method.  In the snippet above, we a have progress visual indicator that shows up while the validation is on going.

In this example, the actual validation is a two step process.  The submitted email address is compared against a regular expression pattern for validity of just the format, and then the domain name is checked for its existence and presence of mail exchanger in the domain through DNS lookup.  See comments in the code below.

package {package-name};

import java.util.Hashtable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

@ManagedBean
@SessionScoped
public class IndexBean implements java.io.Serializable {

    public IndexBean() {
    }
    String emailAddress;

    public void setEmailAddress(String s) {
        emailAddress = s;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void validateEmail() {
        String email = getEmailAddress();
        if (!isValid(email)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
                    email + " is not a valid email address"));

        }
    }

    boolean isValid(String email) {

        // Reqular expression pattern to validate the format submitted
        String validator = "^[_a-zA-Z0-9-]+(\\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+"
                + "(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,})$";

        if (!email.matches(validator)) {
            return false;
        }

        // Split the user and the domain name
        String[] parts = email.split("@");

        boolean retval=true;
        // This is similar to nslookup –q=mx domain_name.com to query
        // the mail exchanger of the domain.
        try {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put("java.naming.factory.initial",
                    "com.sun.jndi.dns.DnsContextFactory");
            DirContext context = new InitialDirContext(env);
            Attributes attributes =
                    context.getAttributes(parts[1], new String[]{"MX"});
            Attribute attribute = attributes.get("MX");
            if (attribute.size() == 0) {
               retval=false;
            }
            context.close();
            return retval;

        } catch (Exception exception) {
            return false;
        }        
    }

    public void process(ActionEvent event) {        
        // Validate again 
        String email = getEmailAddress();
        if (!isValid(email)) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
                    email + " is not a valid email address"));
            return;

        }
        
        // The task;
    }
}

Our regular expression pattern will match an address with dot and hyphen in the user name with 2 characters or more extension in the domain name.   It is also not case sensitive.

That's it Good Luck.

If you like the article, please share.
(Site URL pattern has changed as a result social actions counter was reset.)



Comment icon   Comments (Newest first)