Thursday, April 11, 2013

How to create Credit Card Validator with Facelets

This post shows how to build a custom JSF regex validator to validate Credit Card number with Facelets.

There are different types of Credit Cards, the regex used to validate different types of Credit Card are vary with the types of Credit Card.
Visa ^4[0-9]{12}(?:[0-9]{3})?$
Master Card ^5[1-5][0-9]{14}$
American Express ^3[47][0-9]{13}$
Diners Club ^3(?:0[0-5]|[68][0-9])[0-9]{11}$

For more information about Credit Card Regex, please refer here.
so now let's start to build the Credit Card validator.


Steps:
1. create the validateCreditCard.xhtml in folder <WebContent>/views/validator     and choose the desired Regex based on the Credit Card type.
<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="^4[0-9]{12}(?:[0-9]{3})?$" />

</ui:composition>

2. configure the validateEmail.xhtml in our custom taglib.xml. in this email, is kian.taglib.xml
    <tag>   
        <tag-name>validateCreditCard</tag-name>
        <source>../views/validator/validateCreditCard.xhtml</source>
    </tag>
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 validateCreditCard tag 
<h:inputText value="#{testSessionBean.creditcard}" id="creditcard" 
 validatorMessage="invalid credit card number">
 <kian:validateCreditCard />
</h:inputText>

Output:

p/s: There is another lightweight credit card validation with jQuery here.

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


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...