06
Dec
09

JSF form Validation


This page describes the process of setting up validation in a JSF application.

JSF Standard Validators

JSF comes with standard validators

  1. <validateDoubleRange> : validates to see if the value is a double
  2. <validateLongRange> : validates to see if the value is a long.
  3. <validateLength> : validates to see if the string value for length.

With all of the tags above you can specify a minimum and/or maximum value.

Requirements

  • Maven
  • That’s pretty much it!

Generate the project from an archetype:

mvn archetype:generate -DarchetypeGroupId=org.vtechfw -DarchetypeArtifactId=springmvc-jsf-archetype -DarchetypeVersion=1.0-SNAPSHOT -DarchetypeRepository=http://www.vermatech.com/m2repo

groupId: com.test
artifactId: jsf-validation

The rest of the questions just hit enter choosing the defaults.

test to see if the project comes up

cd jsf-validation;
mvn jetty:run;

Navigate to the application http://localhost:8080/ It should come up with a homepage.

If it does then the test is complete You can continue with the rest of the page.

Message Resources Property File

This file contains all the error messages we will display when validation fails.

src/main/resources/com/test/jsftest/messages.properties

username_required=Username is required
password_required=Password is required
between=Value must be between 2 and 10.

In the resource bundle if the key are composed of multilple word separated by ▒??dot▒??(.),you should represent that key in the JSP page using the format #{msg[‘key’]}.This is a must because ▒??dot▒??(.) is considered as a special character in JSF expression language.

The next step is to get the message bundle property registered in the application.

src/main/webapp/WEB-INF/faces-config.xml

<application>
    <resource-bundle>
        <base-name>
            com.test.jsftest.messages
        </base-name>
        <var>msgs</var>
    </resource-bundle>
</application>

As an alternative you can also type the following in each JSP:

<f:loadBundle basename="com.test.jsftest.messages" var="msgs"/>

Create the Managed Bean Java Class

In the Reference section below get the source for UserManagedBean.java and create it in your source directory.
src/main/java/com/test/jsftest/UserManagedBean.java

package com.test.jsftest;

public class UserManagedBean {
        private String username = "";
        private String password = "";

        public String getUsername() {
                return username;
        }
        public void setUsername(String username) {
                this.username = username;
        }

        public String getPassword() {
                return password;
        }

        public void setPassword(String password) {
                this.password = password;
        }
}

Open up faces-config.xml and insert this right above the managed beans.
src/main/webapp/WEB-INF/faces-config.xml

<managed-bean>
        <managed-bean-name>userManagedBean</managed-bean-name>
        <managed-bean-class>com.test.jsftest.UserManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Setup the Form Page

Next we set up the form page that the user will pull up to enter the username and pssword. The complete source for this page is located in the Reference section. Please copy and paste the source into your webapp/faces directory now.

Once you are done then run the project using

mvn jetty:run

Run The Application

http://localhost:8080/faces/login.faces

Discussions

As you can see below the following is a snippit of what is defined in the login.jsp file.

                <p>Enter your username here: <br/>
                <h:inputText id="username" value="#{username}" size="35"
                        required="true" requiredMessage="#{msgs.username_required}"
                        validatorMessage="#{msgs.between}">
                        <f:validateLength minimum="2" maximum="10" />
                </h:inputText>
                <h:message for="username"/>
                </p>

I am trying to find out how to place 2 and 10 with parameter markers. If you guys know how to do this then please post a comment.

Adding Color

<h:message for="username" style="color: red;"/>

Showing Bulleted list of errors

In order to show a bulleted list of errors on top or bottom of the screen just put this tag at the desired location.

<h:messages showDetail="#{true}" showSummary="#{false}" />

For Reference

In case you got lost the complete source for each file is included here:

src/main/java/com/test/jsftest/UserManagedBean.java

package com.test.jsftest;

public class UserManagedBean {
        private String username = "";
        private String password = "";

        public String getUsername() {
                return username;
        }
        public void setUsername(String username) {
                this.username = username;
        }

        public String getPassword() {
                return password;
        }

        public void setPassword(String password) {
                this.password = password;
        }
}

src/main/webapp/WEB-INF/faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>
<faces-config 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-facesconfig_1_2.xsd"
              version="1.2">
<application>
    <resource-bundle>
        <base-name>
            com.test.jsftest.messages
        </base-name>
        <var>msgs</var>
    </resource-bundle>
</application>

<managed-bean>
        <managed-bean-name>userManagedBean</managed-bean-name>
        <managed-bean-class>com.test.jsftest.UserManagedBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

</faces-config>

src/main/webapp/faces/login.jsp

<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

<f:view>
    <html>
    <head>
        <title>Login Page</title>
    </head>
    <body>
        <h:messages showDetail="#{true}" showSummary="#{false}" />
    <h:form>
                <p>This is a simple login page using Faces.</p>
                <p>Enter your username here: <br/>

                <h:inputText id="username" value="#{userManagedBean.username}" size="35"
                        required="true" requiredMessage="#{msgs.username_required}"
                        validatorMessage="#{msgs.between}">
                        <f:validateLength minimum="2" maximum="10" />
                </h:inputText>
                <h:message for="username" style="color: red;"/>
                </p>
                <p>Enter your password here: <br/>
                <h:inputText id="password" value="#{userManagedBean.password}" size="35"
                        required="true" requiredMessage="#{msgs.password_required}">
                        <f:validateLength minimum="2" maximum="10" />
                </h:inputText> <h:message for="password"/>
                </p>
                <h:commandButton value="Submit" action="submit"/>
    </h:form>
    </body>
    </html>
</f:view>

src/main/resources/com/test/jsftest/messages.properties

username_required=Username is required
password_required=Password is required
between=Value must be between 2 and 10.

Thats all for now!

This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.
Advertisements

0 Responses to “JSF form Validation”



  1. Leave a Comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 74 other followers

December 2009
S M T W T F S
« Nov   Jan »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 801,397 hits

%d bloggers like this: