The Kahimyang Project Logo
Primo's Code Blog
Howtos tips and tricks
The Kahimyang Project

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.

RSS Logo



Comment icon   Comments (Newest first)

Recent posts in Java/JSF category
Blue dot icon Using Rhinoslider with image and youtube content in JSF pages
Blue dot icon A dynamic standard sitemap.xml with Google image extension implemented as a Java Servlet
Blue dot icon Creating a Facebook-like panel with slim scrollbars and infinite scrolling in PrimeFaces
Blue dot icon Generating XML RSS 2 feeds with JDOM 2 with a servlet
Blue dot icon Building a page with infinite scroll in PrimeFaces using Waypoints jQuery plugin
Blue dot icon Implementing a collapsible ui:repeat rows in JSF
Blue dot icon Validating an email address in PrimeFaces p:inputText field with p:ajax





Most popular articles
Blue dot icon Using Expect script to automate SSH logins and do routine tasks accross multiple hosts   (15374)
Blue dot icon How to setup Tomcat 7 as your primary webserver on Debian Squeeze    (14074)
Blue dot icon How to setup FLV streaming with crtmpserver C++ RTMP server   (9841)
Blue dot icon A Java class for sending multipart Email messages through your Gmail account    (6979)
Blue dot icon How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet   (5673)
Blue dot icon Speed up Primefaces page load with p:remoteCommand partial update   (5492)
Blue dot icon Building a mobile website with JSF 2 core and JQuery Mobile 1.0   (5320)
Blue dot icon Google Map-Adding markers, info window, circle, small control, and events in Javascript    (5224)