Showing posts with label Data Validation. Show all posts
Showing posts with label Data Validation. Show all posts

Saturday, May 4, 2013

AJAX validation using Struts2 Framework and XML file with Eclipse Indigo

In this tutorial we are performing Server Side Validation using AJAX validation which will lead to the page to show validation errors without reloading the page.
To perform AJAX Validation we need to use  Struts2-dojo-plugin jar in our project.

so firstly download all Required Jars Without dojo-plugin

Download only Struts2-dojo-plugin-2.3.8.jar if you have already downloaded other jars from previous tutorials
or you can also download source code which is available in the end of this tutorial that contains all jars(with dojo-plugin) including source code



Project Structure in Project Explorer:
reg_form.jsp
create a user input page. 
To work with AJAX, <sx:head> must be in the page. Don't use validate="true" in the form tag because it invokes client side validation(Javascript) before Server Side Validation(AJAX validation) but use validate="true" in the submit tag to perform AJAX validation.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
      <%@ taglib prefix="s" uri="/struts-tags"%>  
      <%@ taglib prefix="sx" uri="/struts-dojo-tags" %>  
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Ajax-Registration-form</title>  
 <sx:head />  
 </head>  
 <body bgcolor="skyblue">  
      <h1>Ajax Registration Form</h1>  
      <hr>  
                  <s:form action="register.action" method="post" >  
            <s:textfield name="Name" label="Name" size="20" />  
            <s:radio name="Gender" label="Gender" list="{'Male', 'Female'}" />  
            <s:select name="Course" label="Course" list="{'Select-Option','B.Tech', 'MCA', 'MSC'}" />  
            <sx:submit align="center" validate="true" />  
         </s:form>  
 </body>  
 </html>  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib prefix="s" uri="/struts-tags"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Hello! <s:property value="name"/></h3></center>  
 </body>  
 </html>  

ContactAction.java
create a Action java class.
 package in.blog.webideaworld;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class ContactAction extends ActionSupport {  
      private String name;  
      private String gender;  
      private String course;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String getGender() {  
           return gender;  
      }  
      public void setGender(String gender) {  
           this.gender = gender;  
      }  
      public String getCourse() {  
           return course;  
      }  
      public void setCourse(String course) {  
           this.course = course;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
 }  

ContactAction-validation.xml
Create validators in XML file and the format for the validatiors xml file is <ActionClassName>-validation.xml
 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"  
           "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">  
 <validators>  
      <field name="Name">  
           <field-validator type="requiredstring">  
                <message>Name is Required.</message>  
           </field-validator>  
           <field-validator type="regex">  
       <param name="expression">[a-zA-Z]{2,20}</param>  
       <message>Please enter valid name.</message>  
     </field-validator>  
      </field>  
      <field name="Gender">  
           <field-validator type="requiredstring">  
                <message>Gender is Required.</message>  
           </field-validator>  
      </field>  
      <field name="Course">  
           <field-validator type="regex">  
       <param name="expression">B.Tech|MCA|MSC</param>  
       <message>Course is required.</message>  
     </field-validator>  
      </field>  
 </validators>  

struts.xml
set result name="success" for success.jsp and name="input" for reg_form.jsp for validation messages to show up on input page.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE struts PUBLIC  
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
   "http://struts.apache.org/dtds/struts-2.0.dtd">  
   <struts>   
   <package name="default" namespace="/" extends="struts-default">  
     <action name="register" class="in.blog.webideaworld.ContactAction" method="execute" >  
     <result name="success">success.jsp</result>  
     <result name="input">reg_form.jsp</result>  
     </action>  
   </package>  
   </struts>  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  <display-name>Struts2_Ajax_Validate</display-name>  
  <welcome-file-list>  
     <welcome-file>reg_form.jsp</welcome-file>  
  </welcome-file-list>  
  <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
      org.apache.struts2.dispatcher.FilterDispatcher  
    </filter-class>  
   </filter>  
   <filter-mapping>  
    <filter-name>struts2</filter-name>  
    <url-pattern>/*</url-pattern>  
   </filter-mapping>  
 </web-app>  

Download Code

View in Browser: 


Registration form:

checking validation without input values:


success page:

Sunday, April 28, 2013

Client side validation on Radio button,Checkbox and Dropdownlist using JavaScript with JSP

In this Tutorial we are performing client side validation using JavaScript with JSP page. and In this post you can learn that how to perform client side validation on Radio buttons,Check-boxes  and on Select tag(Dorpdownlist).

Project Structure in Project Explorer:
 Also read for details of How to create first JSP project



stuform.jsp
create a user input page.
Make sure for script tag for check.js
<script type="text/javascript" src="check.js"></script>
between <head></head> tag
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Register</title>  
 <script type="text/javascript" src="check.js"></script>  
 </head>  
 <body bgcolor="gray">  
 <center >  
 <h1> Registration</h1>  
 <form action="success.jsp" method="post" name="myform">  
 <table bgcolor="lightblue">  
 <tr>  
 <td>Name:</td>  
 <td><input type="text" name="name" id="user"/></td>  
 <td><label id="label1"></label></td>  
 </tr>  
 <tr>  
 <td>Country</td>  
 <td><select id="country" name="country">  
       <option value="" selected>select option</option>  
       <option value="India">INDIA</option>  
       <option value="USA">USA</option>  
       <option value="China">CHINA</option>  
 </select>  
 </td>  
 <td><label id="label2"></label></td>  
 </tr>  
 <tr>  
 <td>Gender</td>  
 <td ><input type="radio" name="gender" value="m" />Male  
   <input type="radio" name="gender" value="f" />Female  
 </td>  
 <td><label id="label3"></label></td>  
 </tr>  
 <tr>  
 <td>Fruit</td>  
 <td><input type="checkbox" name="fruit" value="orange" />Orange  
   <input type="checkbox" name="fruit" value="banana" />Banana  
   <input type="checkbox" name="fruit" value="apple" />Apple  
 </td>  
 <td><label id="label4"></label></td>  
 </tr>  
 <tr>  
 <td><input type="submit" value="Submit" onclick="return validate();"></td>  
 </tr></table>  
 </form>  
 </center></body>  
 </html>  


check.js
write javascript on check.js for validate stuform.jsp and we are performing validation on submit button click.
 f1=1,f2=1,f3=1,f4=1;  
 function validate()  
 {  
   var user=document.getElementById("user").value;  
   var element=document.getElementById("label1");  
    if(user=="")  
     {  
     element.innerHTML="Username Required!";  
     element.style.color="red";  
     f1=1;  
    }  
    else  
     {  
       if(user.search(/^([A-Za-z]){4,15}$/)==-1)  
       {  element.innerHTML="Not a valid User Name.It must be 4-15 characters long";  
         element.style.color="red";  
         f1=1;  
        }  
     else {  
       element.innerHTML="Correct";  
       element.style.color="green";  
        f1=0;  
       }  
     }  
      var con=document.getElementById("country").value;  
      var element=document.getElementById("label2");  
      if(con=="")  
        {  
        element.innerHTML="Country Required!";  
        element.style.color="red";  
        f2=1;  
       }  
       else  
        { element.innerHTML="Correct";  
          element.style.color="green";  
          f2=0;  
        }  
      var gender = document.myform.gender;  
      var element=document.getElementById("label3");  
   for (var i=0; i<gender.length; i++)  
   {  
    if (gender[i].checked)  
         {  
         element.innerHTML="Correct";  
      element.style.color="green";  
         f3=0;  
      break;  
      }  
    else  
         {  
         element.innerHTML="Gender Required!";  
          element.style.color="red";  
         }  
    }  
   var fruit = document.myform.fruit;  
      var element=document.getElementById("label4");  
   for (var i=0; i<fruit.length; i++)  
   {  
    if (fruit[i].checked)  
         {  
         element.innerHTML="Correct";  
      element.style.color="green";  
         f4=0;  
      break;  
      }  
    else  
         {  
         element.innerHTML="Fruit(s) Required!";  
         element.style.color="red";  
          f4=1;  
         }  
    }  
   if(f1==1||f2==1||f3==1||f4==1)  
     {  
       alert("Complete TextBox Conditions!!");  
       return false;  
     }  
     else  
       {  
         return true;  
       }  
 }  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Successfully Registered. </h3></center>  
 </body>  
 </html>  

Download Code

View in Browser: 
checking validation:
 success page: 

Saturday, April 27, 2013

Basic form Validation using Struts2 Framework with validate() method and ActionSupport class

In this Tutorial we are performing server side validation using Struts2 framework with validate() method and for using this method our java class must extend ActionSuppot class.

Project Structure in Project Explorer:
Download Struts2 Jars

Struts2 jars setting, for More Details Read How to set Struts2 Environment

register.jsp
create a user input page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
      <%@ taglib prefix="s" uri="/struts-tags"%>  
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Register</title>  
 </head>  
 <body bgcolor="brown">  
      <h1>Registration</h1>  
      <hr>  
            <s:form action="register.action" method="post" >  
            <s:textfield name="name" label="Name" size="20" />  
            <s:textfield name="age" label="Age" size="20" />  
            <s:textfield name="course" label="Course" size="20" />  
            <s:submit label="Register" align="center" />  
         </s:form>  
 </body>  
 </html>  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib prefix="s" uri="/struts-tags"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Hello! <s:property value="name"/></h3></center>  
 </body>  
 </html>  

ContactAction.java
create a Action java class. Make sure that this java class must extend ActionSupport class else you'll not be able to use validate() method.
 package in.blog.webideaworld;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class ContactAction extends ActionSupport {  
      private String name;  
      private int age;  
      private String course;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
      public String getCourse() {  
           return course;  
      }  
      public void setCourse(String course) {  
           this.course = course;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
      public void validate(){  
           if ( getName().length() == 0 )       
                addFieldError( "name", "Name is required." );  
           if ( getAge() < 18 || getAge() >50 )  
                addFieldError( "age", "Age is required and must be between 18 and 50" );  
           if ( getCourse().length() == 0 )  
                addFieldError( "course", "Course is required." );  
      }  
 }  

struts.xml
set result name="success" for success.jsp and name="input" for register.jsp for validation messages to show up on input page.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE struts PUBLIC  
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
   "http://struts.apache.org/dtds/struts-2.0.dtd">  
   <struts>   
   <package name="default" namespace="/" extends="struts-default">  
     <action name="register" class="in.blog.webideaworld.ContactAction" method="execute" >  
     <result name="success">success.jsp</result>  
     <result name="input">register.jsp</result>  
     </action>  
   </package>  
   </struts>  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  <display-name>Struts2_form_validate</display-name>  
  <welcome-file-list>  
   <welcome-file>register.jsp</welcome-file>  
   </welcome-file-list>  
  <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
      org.apache.struts2.dispatcher.FilterDispatcher  
    </filter-class>  
   </filter>  
   <filter-mapping>  
    <filter-name>struts2</filter-name>  
    <url-pattern>/*</url-pattern>  
   </filter-mapping>  
 </web-app>  

Download Code

View in Browser: 
checking validation:

success page: 

Thursday, April 25, 2013

Validation using Struts2 Framework on Radio button and DropDownList with Eclipse

In this Tutorial we are performing server side validation using Struts2 framework on various fields eg. name,radio button and dropdownlist.

Project Structure in Project Explorer:

Download Struts2 Jars

Struts2 jars setting, for More Details Read How to set Struts2 Environment
Project properties

Web Deployment Assembly


fillform.jsp

create a user input page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
      <%@ taglib prefix="s" uri="/struts-tags"%>  
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Register</title>  
 </head>  
 <body bgcolor="brown">  
      <h1>Registration</h1>  
      <hr>  
            <s:form action="register.action" method="post" >  
            <s:textfield name="Name" label="Name" size="20" />  
            <s:radio name="Gender" label="Gender" list="{'Male', 'Female'}" />  
            <s:select name="Course" label="Course" list="{'Select-Option','B.Tech', 'MCA', 'MSC'}" />  
            <s:submit label="Register" align="center" />  
         </s:form>  
 </body>  
 </html>  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib prefix="s" uri="/struts-tags"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Hello! <s:property value="name"/></h3></center>  
 </body>  
 </html>  

ContactAction.java
create a Action java class.
 package in.blog.webideaworld;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class ContactAction extends ActionSupport {  
      private String name;  
      private String gender;  
      private String course;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public String getGender() {  
           return gender;  
      }  
      public void setGender(String gender) {  
           this.gender = gender;  
      }  
      public String getCourse() {  
           return course;  
      }  
      public void setCourse(String course) {  
           this.course = course;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
 }  

ContactAction-validation.xml
Create validators in XML file and the format for the validatiors xml file is <ActionClassName>-validation.xml
 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"  
           "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">  
 <validators>  
      <field name="Name">  
           <field-validator type="requiredstring">  
                <message>Name is Required.</message>  
           </field-validator>  
           <field-validator type="regex">  
       <param name="expression">[a-zA-Z]{2,20}</param>  
       <message>Please enter valid name.</message>  
     </field-validator>  
      </field>  
      <field name="Gender">  
           <field-validator type="requiredstring">  
                <message>Gender is Required.</message>  
           </field-validator>  
      </field>  
      <field name="Course">  
           <field-validator type="regex">  
       <param name="expression">B.Tech|MCA|MSC</param>  
       <message>Course is required.</message>  
     </field-validator>  
      </field>  
 </validators>  

struts.xml
set result name="success" for success.jsp and name="input" for fillform.jsp for validation messages to show up on input page.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE struts PUBLIC  
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
   "http://struts.apache.org/dtds/struts-2.0.dtd">  
   <struts>   
   <package name="default" namespace="/" extends="struts-default">  
     <action name="register" class="in.blog.webideaworld.ContactAction" method="execute" >  
     <result name="success">success.jsp</result>  
     <result name="input">fillform.jsp</result>  
     </action>  
   </package>  
   </struts>  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  <display-name>Struts2Validate_form</display-name>  
  <welcome-file-list>  
   <welcome-file>fillform.jsp</welcome-file>  
   </welcome-file-list>  
  <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
      org.apache.struts2.dispatcher.FilterDispatcher  
    </filter-class>  
   </filter>  
   <filter-mapping>  
    <filter-name>struts2</filter-name>  
    <url-pattern>/*</url-pattern>  
   </filter-mapping>  
 </web-app>  

Download Code

View in Browser: 
checking validation:

success page: 

Wednesday, April 24, 2013

Validation using Struts2 Framework and XML file with Eclipse Indigo

In this Tutorial we are performing server side validation using Struts2 framework on various fields eg. name,email etc.



Project Structure in Project Explorer:


Firstly Download Struts2 Jars

How to Use Struts2 Jars by two ways:
1. Put all downloaded jars into lib folder of your project.


2. The way i am using Jars, For More Details Read How to set Struts2 Environment
Web Deployment Assembly

contactus.jsp
create a user input page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
      <%@ taglib prefix="s" uri="/struts-tags"%>  
      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Contact Us</title>  
 </head>  
 <body bgcolor="brown">  
      <h1>Contact Information</h1>  
      <hr>  
            <s:form action="customer.action" method="post" >  
            <s:textfield name="Name" key="label.name" size="40" />  
            <s:textfield name="Age" key="label.age" size="40" />  
            <s:textfield name="Email" key="label.email" size="40" />  
             <s:textarea name="Message" key="label.msg" rows="10" cols="40" ></s:textarea>  
            <s:submit key="label.customer" align="center" />  
         </s:form>  
 </body>  
 </html>  

success.jsp
create a user's success page.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
   <%@ taglib prefix="s" uri="/struts-tags"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Hello! <s:property value="name"/></h3></center>  
 </body>  
 </html>  

ContactAction.java
create a Action java class.
 package in.blog.webideaworld;  
 import com.opensymphony.xwork2.ActionSupport;  
 @SuppressWarnings("serial")  
 public class ContactAction extends ActionSupport {  
      private String name;  
      private int age;  
      private String email;  
      private String message;  
      public String getName() {  
           return name;  
      }  
      public void setName(String name) {  
           this.name = name;  
      }  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
      public String getEmail() {  
           return email;  
      }  
      public void setEmail(String email) {  
           this.email = email;  
      }  
      public String getMessage() {  
           return message;  
      }  
      public void setMessage(String message) {  
           this.message = message;  
      }  
      public String execute() throws Exception{  
           return SUCCESS;  
      }  
 }  

ContactAction-validation.xml
Create validators in XML file and the format for the validatiors xml file is <ActionClassName>-validation.xml
 <!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"  
           "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">  
 <validators>  
      <field name="Name">  
           <field-validator type="requiredstring">  
                <message key="errors.required" />  
           </field-validator>  
           <field-validator type="regex">  
       <param name="expression">[a-zA-Z]{2,20}</param>  
       <message key="errors.invalid" />  
     </field-validator>  
      </field>  
      <field name="Age">  
    <field-validator type="required">  
      <message key="errors.required" />  
    </field-validator>  
    <field-validator type="int">  
      <param name="min">18</param>  
      <param name="max">100</param>  
      <message key="errors.agerange" />  
    </field-validator>  
  </field>  
      <field name="Email">  
           <field-validator type="requiredstring">  
                <message key="errors.required" />  
           </field-validator>  
           <field-validator type="email">  
                <message key="errors.invalid" />  
           </field-validator>  
      </field>  
      <field name="Message">  
           <field-validator type="requiredstring">  
                <message key="errors.required" />  
           </field-validator>  
        <field-validator type="stringlength">  
       <param name="minLength">4</param>  
       <param name="maxLength">200</param>  
       <message key="errors.msgrange"/>  
   </field-validator>  
      </field>  
 </validators>  

ApplicationResources.properties
 label.name=Name  
 label.age=Age  
 label.email=Email  
 label.msg=Message  
 label.customer=Send  
 errors.invalid=${getText(fieldName)} is invalid.  
 errors.required=${getText(fieldName)} is required.  
 errors.agerange=Age must be between ${min} and ${max}, current value is ${Age}.  
 errors.msgrange=Message length must be between ${minLength} to ${maxLength} characters.  

struts.xml
set result name="success" for success.jsp and name="input" for contactus.jsp for validation messages to show up on input page.
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE struts PUBLIC  
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
   "http://struts.apache.org/dtds/struts-2.0.dtd">  
   <struts>  
        <constant name="struts.custom.i18n.resources" value="ApplicationResources" />   
   <package name="default" namespace="/" extends="struts-default">  
     <action name="customer" class="in.blog.webideaworld.ContactAction" method="execute" >  
     <result name="success">success.jsp</result>  
     <result name="input">contactus.jsp</result>  
     </action>  
   </package>  
   </struts>  

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  <display-name>StrutsValidate</display-name>  
  <welcome-file-list>  
   <welcome-file>contactus.jsp</welcome-file>  
   </welcome-file-list>  
  <filter>  
    <filter-name>struts2</filter-name>  
    <filter-class>  
      org.apache.struts2.dispatcher.FilterDispatcher  
    </filter-class>  
   </filter>  
   <filter-mapping>  
    <filter-name>struts2</filter-name>  
    <url-pattern>/*</url-pattern>  
   </filter-mapping>  
 </web-app>  

Download Code

View in Browser: 
checking validation without input values:
checking validation with input values:
success page:


Tuesday, April 16, 2013

Validation for Email and Confirm Password using JavaScript, Regular Expression on JSP page

In this Tutorial we are performing validation on textbox for email and re-type password using Regular Expression with JavaScript. We are performing our task with Eclipse IDE and for user's view we are using JSP.

Project Explorer View:


register.jsp
If we want to write JavaScript on same html page then it must be inside <head> </head> tag.
for green tick mark we are using green.jpg image which you can see in project explorer view.
If all available text-box conditions are true then on submit button click page will redirect to success.jsp
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
      pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>User Registration page</title>  
 <script type="text/javascript">  
 f1=1,f2=1,f22=1;  
 function checkemail()  
 {  
   var email=document.getElementById("email").value;  
   var element=document.getElementById("label1");  
   if(email=="")  
     { element.innerHTML="Email Id Required!";  
     element.style.color="red";  
     document.getElementById("img1").style.visibility='hidden';  
     document.getElementById("label1").style.visibility='visible';  
     f1=1;  
     }  
   else  
     {  if(email.search(/^\w+([.-]\w+)*@([A-Za-z0-9\-]){2,12}\.([A-Za-z]{2,4})$/)==-1)  
       {  element.innerHTML="Not a valid email format. Must be email@host.domain";  
         element.style.color="red";  
         document.getElementById("img1").style.visibility='hidden';  
         document.getElementById("label1").style.visibility='visible';  
         f1=1;  
        }  
     else{  
          document.getElementById("img1").style.visibility='visible';  
          document.getElementById("label1").style.visibility='hidden';  
       f1=0;  
       }  
      }  
 }  
 function checkpass1()  
 {  
   var pass1=document.getElementById("pass1").value;  
   var pass2=document.getElementById("pass2").value;  
   var element=document.getElementById("label2");  
   if(pass1=="")  
     {element.innerHTML="Password Required!";  
     element.style.color="red";  
     document.getElementById("img2").style.visibility='hidden';  
     document.getElementById("label2").style.visibility='visible';  
     f2=1;  
   }  
   else  
   {   
     if(pass1.length<4||pass1.length>15)  
     {  
       element.innerHTML="Password must be 4-15 characters long";  
       element.style.color="red";  
       document.getElementById("img2").style.visibility='hidden';  
       document.getElementById("label2").style.visibility='visible';  
       f2=1;  
     }  
     else  
     {document.getElementById("img2").style.visibility='visible';  
        document.getElementById("label2").style.visibility='hidden';  
       f2=0;  
     }  
   }  
   if(pass2=="")  
   {//no f2 set  
        document.getElementById("img2").style.visibility='hidden';  
     document.getElementById("label2").style.visibility='visible';  
   }  
   else if(pass1!=pass2)  
   { element.innerHTML="Password Not Matched!";  
        element.style.color="red";  
        document.getElementById("img2").style.visibility='hidden';  
        document.getElementById("label2").style.visibility='visible';  
        f2=1;  
   }  
   else  
   {document.getElementById("img2").style.visibility='visible';  
      document.getElementById("label2").style.visibility='hidden';  
       f2=0;  
   }  
 }  
 function checkpass2()  
 {  
   var pass1=document.getElementById("pass1").value;  
   var pass2=document.getElementById("pass2").value;  
   var element=document.getElementById("label2");  
   if(pass1==""&&pass2=="")  
   { element.innerHTML="Password Required!";  
     element.style.color="red";  
     document.getElementById("img2").style.visibility='hidden';  
     document.getElementById("label2").style.visibility='visible';  
     f22=1;  
   }  
   else if(pass2.length<4||pass2.length>15)  
   {  
       element.innerHTML="Password must be 4-15 characters long";  
       element.style.color="red";  
       document.getElementById("img2").style.visibility='hidden';  
       document.getElementById("label2").style.visibility='visible';  
       f22=1;  
   }  
   else if(pass1!=pass2)  
   { element.innerHTML="Password Not Matched!";  
     element.style.color="red";  
     document.getElementById("img2").style.visibility='hidden';  
     document.getElementById("label2").style.visibility='visible';  
     f22=1;  
   }  
   else  
   {document.getElementById("img2").style.visibility='visible';  
      document.getElementById("label2").style.visibility='hidden';  
     f22=0;  
   }  
 }  
 function validate()  
 {  
   if(f1==1||f2==1||f22==1)  
     {  
       alert("Complete TextBox Conditions!!");  
       return false;  
     }  
     else  
       {  
         return true;  
       }  
 }  
 </script>  
 </head >  
 <body bgcolor="black">  
 <form action="success.jsp" method="post">  
           <table bgcolor="white" align="center">  
             <tr>  
                     <td colspan="3"><h1>User Registration</h1></td>  
                </tr>  
                <tr>  
                     <td>Email:</td>  
                     <td><input type="text" id="email" onblur="checkemail();"></td>  
                     <td><img src="green.jpg" id="img1" style="visibility:hidden"><label id="label1"></label></td>  
                </tr>  
                <tr>  
                     <td>Password:</td>  
                     <td><input type="password" id="pass1" onblur="checkpass1();" /></td>  
                </tr>  
                <tr>  
                     <td>Confirm Password:</td>  
                     <td><input type="password" id="pass2" onblur="checkpass2();"/></td>  
                     <td><img src="green.jpg" id="img2" style="visibility:hidden"><label id="label2"></label></td>  
                </tr>  
                <tr>  
                     <td><input type="submit" value="Register" onclick="return validate();"/></td>  
                </tr>  
           </table>  
 </form>  
 </body>  
 </html>  

success.jsp
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>success</title>  
 </head>  
 <body bgcolor="lightblue">  
 <center><h3>  
 Your record registered successfully.</h3></center>  
 </body>  
 </html>  


View in Browser:

Friday, December 7, 2012

Validation on TextField using JavaScript and Print command using servlet on NetBeans



Here in this Tutorial we are using JavaScript with Regular Expreesion to perform validation on TextField and Invoking Print a page command on Servlet using netbeans.

Project View on Project Explorer on Completion of This Tutorial
index.jsp
In index.jsp page in form tag printing is url pattern of printing.java page which we are passing in Action property which redirects index.jsp to printing.java
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
   "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Registration Page</title>  
     <script type="text/javascript">  
       f1=1,f2=1;  
       function checkfname()  
       {  
         var fname=document.getElementById("fname").value;  
         var element=document.getElementById("label1");  
          if(fname=="")  
           {element.innerHTML="First Name Required!";  
           element.style.color="red";  
           f1=1;  
         }  
         else if(fname.length<4||fname.length>10)  
           { element.innerHTML="First Name must be 4-10 characters long";  
           element.style.color="red";  
           f1=1;  
         }  
         else  
           {  
             if(fname.search(/^([A-Za-z]){1,}$/)==-1)  
             {  element.innerHTML="Not a valid First Name";  
               element.style.color="red";  
               f1=1;  
              }  
           else {  
             element.innerHTML="Correct";  
             element.style.color="green";  
             f1=0;  
             }  
           }  
       }  
       function checklname()  
       {  
         var lname=document.getElementById("lname").value;  
         var element=document.getElementById("label2");  
          if(lname=="")  
           {element.innerHTML="Last Name Required!";  
           element.style.color="red";  
           f2=1;  
         }  
         else if(lname.length<4||lname.length>10)  
           { element.innerHTML="Last Name must be 4-10 characters long";  
           element.style.color="red";  
           f2=1;  
         }  
         else  
           {  
             if(lname.search(/^([A-Za-z]){1,}$/)==-1)  
             {  element.innerHTML="Not a valid Last Name";  
               element.style.color="red";  
               f2=1;  
              }  
           else {  
             element.innerHTML="Correct";  
             element.style.color="green";  
             f2=0;  
             }  
           }  
       }  
       function validate()  
       {  
         if(f1==1||f2==1)  
           {  
             alert("Entry not valid!!");  
             return false;  
           }  
           else  
             {  
               return true;  
             }  
       }  
     </script>  
   </head>  
   <body>  
     <h1>Registration</h1>  
     <form action="printing">  
     <table><tr><td>First Name:<input type="text" id="fname" name="t1" onblur="checkfname();"></td><td><label id="label1"/></td></tr>  
     <tr><td>Last Name:<input type="text" id="lname" name="t2" onblur="checklname();"></td><td><label id="label2"/></td></tr>  
     <tr><td><input type="submit" value="submit" onclick="return validate();" ></td></tr></table>  
     </form>  
   </body>  
 </html>  

printing.java
Here we are using window.print() command on print button click to print output page.
 import java.io.*;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.*;  
 public class printing extends HttpServlet {  
   protected void doGet(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
     response.setContentType("text/html;charset=UTF-8");  
     PrintWriter out = response.getWriter();  
     String s1=request.getParameter("t1");  
     String s2=request.getParameter("t2");  
     try {  
       out.println("First Name:"+s1+"<br>");  
       out.println("Last Name:"+s2+"<br>");  
       out.println("<input type=submit value=print onclick=window.print()>");  
     } finally {   
       out.close();  
     }  
   }   
  }  


web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" 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">  
   <servlet>  
     <servlet-name>printing</servlet-name>  
     <servlet-class>printing</servlet-class>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>printing</servlet-name>  
     <url-pattern>/printing</url-pattern>  
   </servlet-mapping>  
   <session-config>  
     <session-timeout>  
       30  
     </session-timeout>  
   </session-config>  
   <welcome-file-list>  
     <welcome-file>index.jsp</welcome-file>  
   </welcome-file-list>  
 </web-app>  

Download Code Link 1
Download Code Link 2
output:







Popular Posts