JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







JSF Validators

JSF validation is used to make sure that the component is going to obtain
the expected content, such as:
  • Length is between 1 and 10
  • Float is between 2.0 and 10.0
  • Email address is in correct format etc.
JavaServer Faces has built-in mechanisms that let you carry out the following
validations:
  • Checking the length of a string
  • Checking limits for a numerical value (for example, > 0 or ≤ 100)
  • Checking that a value has been supplied

You can implement it by two ways:
  • Using standard validators supplied by JSF and
  • Creating your own custom validators.
Standard validation


  • All the standard validator tags have minimum and maximum attributes.
  • You need to supply one or both of these attributes.
For Example:-
<h:inputText id="amount" value="#{payment.amount}">
<f:validateLongRange minimum="10" maximum="10000"/>
</h:inputText>
The validator checks that the supplied value is ≥ 10 and ≤ 10000.

Example:1

index.jsp
<html>
   <%taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css"/>
         <title><h:outputText value="#{msgs.title}"/></title>
      </head>
      <body>
         <h:form>
            <h1><h:outputText value="#{msgs.enterPayment}"/></h1>
            <h:panelGrid columns="3">
               <h:outputText value="#{msgs.amount}"/>
               <h:inputText id="amount" label="#{msgs.amount}"
                     value="#{payment.amount}" required="true"
                  <f:convertNumber minFractionDigits="2"/>
                  <f:validateDoubleRange minimum="10" maximum="10000"/>     
               </h:inputText>
               <h:message for="amount" styleClass="errorMessage"/>

               <h:outputText value="#{msgs.creditCard}"/>
               <h:inputText id="card" label="#{msgs.creditCard}"
                     value="#{payment.card}" required="true"
                  <f:validateLength minimum="13"/>
                  <f:attribute name="requiredMessage"
value=
"#{msgs.cardRequired}"/>
               </h:inputText>
               <h:message for="card" styleClass="errorMessage"/>

               <h:outputText value="#{msgs.expirationDate}"/>
               <h:inputText id="date" label="#{msgs.expirationDate}"
                  value="#{payment.date}" required="true"
                  <f:convertDateTime pattern="MM/yyyy"/>
               </h:inputText>
               <h:message for="date" styleClass="errorMessage"/>
            </h:panelGrid>
            <h:commandButton value="Process"
action="process"/>
            <h:commandButton value="Cancel"
action="cancel" immediate="true"/>
         </h:form>
      </body>
   </f:view>
</html>


PymentBean.java
package myjsf;
import java.util.Date;

public class PaymentBean {
   private double amount;
   private String card = "";
   private Date date = new Date();

   // PROPERTY: amount
   public void setAmount(double newValue) { amount = newValue; }
   public double getAmount() { return amount; }

   // PROPERTY: card
   public void setCard(String newValue) { card = newValue; }
   public String getCard() { return card; }

   // PROPERTY: date
   public void setDate(Date newValue) { date = newValue; }
   public Date getDate() { return date; }
}

message.properties
title=An Application to Test Validation
enterPayment=Please enter the payment information 
amount=Amount
creditCard=Credit Card
expirationDate=Expiration date (Month/Year)
paymentInformation=Payment information
canceled=The transaction has been canceled.
back=Back
cardRequired=A credit card number is required.

faces-config.xml
<?xml version="1.0"?>
<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">
   <navigation-rule>
      <from-view-id>/index.jsp</from-view-id>
      <navigation-case>
         <from-outcome>process</from-outcome>
         <to-view-id>/result.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
         <from-outcome>cancel</from-outcome>
         <to-view-id>/canceled.jsp</to-view-id>
      </navigation-case>
   </navigation-rule>

   <navigation-rule>
      <navigation-case>
         <from-outcome>back</from-outcome>
         <to-view-id>/index.jsp</to-view-id>
      </navigation-case>
   </navigation-rule>
   
   <managed-bean> 
      <managed-bean-name>payment</managed-bean-name>
      <managed-bean-class>myjsf.PaymentBean</managed-bean-class
      <managed-bean-scope>session</managed-bean-scope> 
   </managed-bean>

   <application>
      <resource-bundle>
         <base-name>myjsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
   </application>
</faces-config>

result.jsp
<html>
   <%taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css"/>
         <title><h:outputText value="#{msgs.title}"/></title>
      </head>
      <body>
         <h:form>
            <h1><h:outputText value="#{msgs.paymentInformation}"/></h1>
            <h:panelGrid columns="2">
               <h:outputText value="#{msgs.amount}"/>
               <h:outputText value="#{payment.amount}"
                  <f:convertNumber type="currency"/>
               </h:outputText>

               <h:outputText value="#{msgs.creditCard}"/>
               <h:outputText value="#{payment.card}"/>

               <h:outputText value="#{msgs.expirationDate}"/>
               <h:outputText value="#{payment.date}"
                  <f:convertDateTime pattern="MM/yyyy"/>
               </h:outputText>
            </h:panelGrid>
            <h:commandButton value="Back" action="back"/>
         </h:form>
      </body>
   </f:view>
</html>

cancel.jsp
<html>
   <%taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css"/>
         <title><h:outputText value="#{msgs.title}"/></title>
      </head>
      <body>
         <h:form>
            <h:outputText value="#{msgs.canceled}"/>
            <br/>
            <h:commandButton value="#{msgs.back}" action="back"/>
         </h:form>
      </f:view>
   </body>
</html>

style.css
.errorMessage {
   color:red; 
}

web.xml
<?xml version="1.0"?>
<web-app 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-app_2_5.xsd"
  version="2.5">
   <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>   

   <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.faces</url-pattern>
   </servlet-mapping>  

   <welcome-file-list>
      <welcome-file>/index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

Directory Structure



Output:-
when we procees without any entry......




When the Amount is not valid numaric .....


when the Amount greater than 10000 or not in between range....



When the credit card number is not valid...



When all the input are correct.........



Download Source
Download War

Custom validation
  • If validation for the component value is not supported by the standard
    validators then you will need to create your own validator.
  • For example, you can create email validator to validate the email text
    entered by the user i.e. whether the email id is in correct format.
  • Using custom validator you will be able to display your own validation
    error message.
Creating a custom validator
  • Create a class that implements the javax.faces.validator.Validator
    interface.
  • Implement the validate() method (defined in Validator interface).
  • Register this validator in the configuration file "faces-config.xml".
  • Use this validator by <f:validator/> tag in the JSP page. Use
    <h:message> tag in the jsp page to display the error message.

Example:- In this example we are validating the em ail id of the user through our custom validator...!

index.jsp
<html>
   <%taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css"/>
         <title><h:outputText value="#{msgs.title}"/></title>
      </head>
      <body>
         <h:form>
            <h1><h:outputText value="#{msgs.enterName}"/></h1>
            <h:panelGrid columns="2">
               <h:outputText value="#{msgs.name}"/>
               <h:inputText id="name" label="#{msgs.name}"
                value="#{student.name}" required="true"
               </h:inputText>
      
               <h:outputText value="#{msgs.phone}"/>
               <h:inputText id="phone" label="#{msgs.phone}"
                  value="#{student.phonenumber}" required="true"
               </h:inputText>
               
               <h:outputText value="#{msgs.email}"/>
               <h:inputText id="email" label="#{msgs.email}"
                  value="#{student.email}" required="true"
                  <f:validator validatorId="checkemail"/> 
               </h:inputText>
               <h:message for="email" styleClass="errorMessage"/>
               
            </h:panelGrid>
            <h:commandButton value="Process" action="process"/>
            <h:commandButton value="Cancel" action="cancel" immediate="true"/>
         </h:form>
      </body>
   </f:view>
</html>

EmailValidator.java
package myvalidator;

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.Validator;
import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {

  @Override
  public void validate(FacesContext context, UIComponent component,
      Object valuethrows ValidatorException {
        String enteredEmail = (String)value;
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(enteredEmail);
        boolean matchFound = m.matches();
        if (!matchFound) {
        FacesMessage message = new FacesMessage();
        message.setSummary("Invalid Email ID.");
        throw new ValidatorException(message);
        }
        }
    

}

Student.java
package myjsf;
import java.util.Date;

public class Student{
  private String name;
  private String phonenumber;
  private String email;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPhonenumber() {
    return phonenumber;
  }
  public void setPhonenumber(String phonenumber) {
    this.phonenumber = phonenumber;
  }
  public String getEmail() {
    return email;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  
  
  }

faces-config.xml
<?xml version="1.0"?>
<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">
   <navigation-rule>
      <from-view-id>/index.jsp</from-view-id>
      <navigation-case>
         <from-outcome>process</from-outcome>
         <to-view-id>/result.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
         <from-outcome>cancel</from-outcome>
         <to-view-id>/canceled.jsp</to-view-id>
      </navigation-case>
   </navigation-rule>

   <navigation-rule>
      <navigation-case>
         <from-outcome>back</from-outcome>
         <to-view-id>/index.jsp</to-view-id>
      </navigation-case>
   </navigation-rule>
   
   <managed-bean> 
      <managed-bean-name>student</managed-bean-name>
      <managed-bean-class>myjsf.Student</managed-bean-class
      <managed-bean-scope>session</managed-bean-scope> 
   </managed-bean>

   <application>
      <resource-bundle>
         <base-name>myjsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
   </application>
   
   <validator>
<validator-id>checkemail</validator-id>
<validator-class>myvalidator.EmailValidator</validator-class>
</validator>
</faces-config>

web.xml
<?xml version="1.0"?>
<web-app 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-app_2_5.xsd"
  version="2.5">
   <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>   

   <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.faces</url-pattern>
   </servlet-mapping>  

   <welcome-file-list>
      <welcome-file>/index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

result.jsp
<html>
   <%taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   <%taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   <f:view>
      <head>
         <link href="styles.css" rel="stylesheet" type="text/css"/>
         <title><h:outputText value="#{msgs.title}"/></title>
      </head>
      <body>
         <h:form>
            <h1><h:outputText value="#{msgs.studentInformation}"/></h1>
            <h:panelGrid columns="2">
               <h:outputText value="#{msgs.name}"/>
               <h:outputText value="#{student.name}"/> 
               <h:outputText value="#{msgs.phone}"/>
               <h:outputText value="#{student.phonenumber}"/>

               <h:outputText value="#{msgs.email}"/>
               <h:outputText value="#{student.email}"/> 
                  
               
            </h:panelGrid>
            <h:commandButton value="Back" action="back"/>
         </h:form>
      </body>
   </f:view>
</html>

messages.properties
title=An Application to Test Validation
enterName=Please enter the Student information 
name=Name
phone=Phone Number
studentInformation=Student Information
back=Back
email=Email ID

Directory Structure


Output:-









Download Source with lib
Download Source without lib