Today’s topic is JSF 2 custom validation. We are going to show you how to create and use a custom JSF 2 validator – the email address validator. Our sample application is consists of a simple form which takes email data. Email data is being validated by the JSF 2 validation mechanisms – custom EmailValidator
class.
Our sample application looks like this:
This project was developed using the Eclipse IDE. To find out how to configure your development environment please refer to our earlier tutorials:
Maven 3 installation and configuration
Maven 3 Eclipse plugin setup
To see how to create a base project that was used in this tutorial please visit our earlier tutorial and follow the 7 steps listed there – Creating Maven 3 WebApp project.
The application project structure looks like this:
pom.xml
Here is project’s pom.xml
file. Since we are using JBoss AS 7.x
to run this application all the JSF2 artifacts
are marked as provided
. You don’t need them in the resulting WAR archive. JBoss comes bundled with JSF 2 implementation. Today all the popular JEE Application servers like WebLogic, WebSphere, Glassfish etc. comes bundled with the JSF 2 implementation.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itcuties.examples.webapps</groupId> <artifactId>jsf2-form-email-validation-example</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>jsf2-form-email-validation-example</name> <url>http://www.itcuties.com</url> <dependencies> <!-- JSF 2 API --> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.0-m07</version> <scope>provided</scope> </dependency> <!-- JSF 2 Implementation --> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.0-m07</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>validation</finalName> </build> </project>
web.xml
You need to configure JSF2 in your web.xml
file. JSF2 is implemented as a Servlet which processes URL in your application, in our case we map every URL that ends with *.xhtml
to the Faces Servlet
.
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>JSF 2 Form Email Validation example</display-name> <!-- The welcome page --> <welcome-file-list> <welcome-file>index.xhtml</welcome-file> </welcome-file-list> <!-- Start JSF --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- JSF URL mapping --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>
EmailBean.java
This is a simple JSF 2 bean which is indicated with the @ManagedBean
. This class has the email
attribute which is set through the http form. The submit()
method is mapped as a form action.
The important thing to mention here is that the submit()
method is going to be called by the JSF 2 framework only when the email address entered in the form is valid.
package com.itcuties.validation.beans; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; @ManagedBean public class EmailBean { private String email; public void submit() { System.out.println("EmailBean:: received valid email: " + email); // Set the message here FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Email is OK", "ok"); FacesContext.getCurrentInstance().addMessage(null, msg); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
EmailValidator.java
This is the main class of this tutorial. This class implements the validation logic, it checks if the email address is valid or not.
To write your own JSF2 custom validation class all you need to do is implementing the javax.faces.validator.Validator
interface. You need to implement the validate
method and annotated your class with the @FacesValidator
annotation providing the validator id which you are going to use in the view. The idea is that if something is wrong with the validated value the javax.faces.validator.ValidatorException
needs to be thrown. Take a look at our example which is using Java Regex mechanisms which we have discussed in our earlier tutorial – Java Regular Expression
package com.itcuties.validation.validators; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; @FacesValidator("emailValidator") public class EmailValidator implements Validator { private final static String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private final static Pattern EMAIL_COMPILED_PATTERN = Pattern.compile(EMAIL_PATTERN); /** * Validate method. */ public void validate(FacesContext fc, UIComponent c, Object o) throws ValidatorException { // No value is not ok if (o == null || "".equals((String)o)) { FacesMessage msg = new FacesMessage("No email value!", "Email Validation Error"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } // The email matcher Matcher matcher = EMAIL_COMPILED_PATTERN.matcher((String)o); if (!matcher.matches()) { // Email doesn't match FacesMessage msg = new FacesMessage("Invalid email value!", "Email Validation Error"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } }
index.xhtml
Here is our sample view. It consists of the form, an inputText and a button component. If you want to validate a field just add a f:validator
tag to it providing validator id.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Email Validation Form</title> </h:head> <h:body> <h3>Email Validation Form</h3> <h:form> <h:inputText value="#{emailBean.email}"> <f:validator validatorId="emailValidator" /> </h:inputText> <h:commandButton id="button" value="Submit and Validate" action="#{emailBean.submit}" /> <h:messages /> </h:form> </h:body> </html>
Running the application
To build this code you need to call the mvn package
command. As a result the validation.war
package gets created in the target
directory of your project. Deploy the WAR package on the application server. As mentioned before, the application server you are deploying your application to has to have a JSF implementation in it’s classpath. Using JBoss, WebLogic, WebSphere, Glassfish or any other application platform that comes bundled with the JSF 2 implementation is recommended.
Download this sample code here.
This code is available on our GitHub repository as well.
The post JSF 2 custom validation – the email validation example appeared first on Programmer's lounge.