Tuesday, April 9, 2013

Easy JSF Email validator with Facelets

This post shows how to build a custom JSF regex validator to validate email address with Facelets.
Building email validator with Facelets is very easy if compare to building email validator with JSF component classes.

Steps:
1. create the validateEmail.xhtml in folder <WebContent>/views/validator
    Regex here could be changed to any desired format.

<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html">
    <f:validateRegex
        pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />

</ui:composition>

2. configure the validateEmail.xhtml in our custom taglib.xml. in this email, is kian.taglib.xml

<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd" 
    version="2.0">  

    <namespace>http://kian/jsf/composite/cc</namespace> 
    <composite-library-name>kian</composite-library-name>   

    <tag>  
        <tag-name>validateEmail</tag-name>
        <source>../views/validator/validateEmail.xhtml</source>
    </tag>   

</facelet-taglib>

If your project is not already configured for custom namespace, please refer How to create custom taglib descriptor in a JSF project

3. use the new tag - validateEmail in xhml.
a) import the custom namespace in which xhtml need the custom tag
 <f:view
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:kian="http://kian/jsf/composite/cc">

b) invoke the new validateEmail tag
<h:inputText value="#{testSessionBean.email}" id="email" 
    validatorMessage="invalid email">
    <kian:validateEmail />
</h:inputText>

Output:
validate email failed

There is another email validation with jQuery here.

Other input validation example in JSF:
  - Credit Card
  - Number
  - Number, with regular expression


Done!!


LinkWithin

Related Posts Plugin for WordPress, Blogger...