Struts built-in validation with example

Here we explain the form validation using strut built-in fatalities. Let us suppose that we have to validate the four form field – username, password, email and data of birth. As per our requirement we have to validate---
1.All fields should be mandatory.
2.Username and password have minimum length(suppose both are 5-digits)
3.Email Id should be proper format.
4.And data of birth should in dd/mm/yyyy format.

So our user interface is look like this:

Suppose we submit all blank fields so the user interface is


Now we submit username and password less the 5-digits, email id not in proper format and data of birth in different format so user interface now is


Now our main purpose is to validate these fields using strut built-in facilities, for this first of all we have to add one plug-in called ValidatorPlugIn the full class name is 
org.apache.struts.validator.ValidatorPlugIn in struts-config.xml file

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  <set-property  property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/myvalidations.xml"/>
  </plug-in>

In the above code of line we can see that there is a set-property tag in which the values are mentioned two xml files-one is  validator-rules.xml and another is myvalidations.xml.

In Validator-rules.xml files built-in validation rules are defined in this file you can also add customized validation if you required. Another file is myvalidations.xml  in this file we can set form name, fields names etc.

For proper validation message we use the one properties file called ApplicationResources, in this file we can define the message format.
Now here we give one example with codes
We are use three jsp files for user interface – index.jsp, home.jsp and registration.jsp.

Action class is RegisterAction.java and form class is RegisterForm.java and resource file is ApplicationResource.properties.

He we show you directory structure so that you can all files:

Now see the code of all files one by one-

index.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">
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<body>
<h1><html:link forward="register">Click Here for Registration</html:link></h1>
</body>
</html>
register.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">
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<body>
<h1>Registration Form</h1>
<html:form action="/RegSubmit.do">
<table>
 
 <tr><td>Username</td>
     <td><html:text property="username"/></td>
     <td><html:errors property="username"/></td>
 </tr> 
 <tr><td>Password</td>
     <td><html:password property="password"/></td>
     <td><html:errors property="password"/></td>
 </tr> 
 <tr><td>Email</td>
     <td><html:text property="email"/></td>
     <td><html:errors property="email"/></td>
 </tr> 
 <tr><td>Date Of Birth</td>
     <td><html:text property="dob"/>(20/05/1985)</td>
     <td><html:errors property="dob"/></td>
 </tr>
 
   
 <tr><td colspan="3" align="center"><html:submit value="Register"/></td>
 </tr>
</table>

</html:form>
</body>
</html>
home.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">
<%@page isELIgnored="false"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html>
<body>
<h1>Validation is done</h1>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

RegisterAction.java
package com.javaforecast4u;
import org.apache.struts.action.*;
import javax.servlet.http.*;

public class RegisterAction extends Action
{
 public ActionForward execute(ActionMapping am,ActionForm af,HttpServletRequest req,HttpServletResponse res)throws Exception
 {
  String status="home";
  RegisterForm rf=(RegisterForm)af;
 
  System.out.println(rf.getUsername());
  System.out.println(rf.getPassword());
  System.out.println(rf.getEmail());
  System.out.println(rf.getDob());
  return am.findForward(status);
 }
}

RegisterForm.java
package com.javaforecast4u;
import java.util.Date;
import org.apache.struts.validator.ValidatorForm;

public class RegisterForm extends ValidatorForm
{
 private String sid;
 private String username;
 private String password;
 private String email;
 private String dob;
 private long phone;
 private double fee;
 private String quali;
 private String course[];
 private String gender;
public String getSid() {
     return sid;
}
public void setSid(String sid) {
     this.sid = sid;
}
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;
}
public String getEmail() {
     return email;
}
public void setEmail(String email) {
     this.email = email;
}
public String getDob() {
     return dob;
}
public void setDob(String dob) {
     this.dob = dob;
}
public long getPhone() {
     return phone;
}
public void setPhone(long phone) {
     this.phone = phone;
}
public double getFee() {
     return fee;
}
public void setFee(double fee) {
     this.fee = fee;
}
public String getQuali() {
     return quali;
}
public void setQuali(String quali) {
     this.quali = quali;
}
public String[] getCourse() {
     return course;
}
public void setCourse(String[] course) {
     this.course = course;
}
public String getGender() {
     return gender;
}
public void setGender(String gender) {
     this.gender = gender;
}

}

ApplicationResources.properties
errors.required=<font color=red size=5>{0} is required.</front>
errors.minlength=<font color=red size=5>{0} length must be minimum characters{1}</front>
errors.maximum=<font color=red size=5>{0} length must be maximum characters{2}</front>
errors.long=<font color=red size=5>{0} must be a long.</front>
errors.double=<font color=red size=5>{0} must be a double.</front>
errors.date=<font color=red size=5>{0} is not Valid Date.</front>
errors.email=<font color=red size=5>{0} is an invalid.</front>
Struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <data-sources />
  <form-beans >
   <form-bean name="regForm" type="com.javaforecast4u.RegisterForm"/>
  </form-beans>
 
  <global-exceptions/>
   <global-forwards>
   <forward name="register" path="/register.jsp"/>
   <forward name="home" path="/home.jsp"/>
  </global-forwards>
  
  <action-mappings>
   <action path="/RegSubmit" name="regForm" type="com.javaforecast4u.RegisterAction" validate="true" input="/register.jsp"/>
  </action-mappings>
 
  <message-resources parameter="com.javaforecast4u.ApplicationResources" />
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  <set-property  property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/myvalidations.xml"/>
  </plug-in>
</struts-config>

myvalidations.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation/DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<form-validation>
 <formset>
  <form name="regForm">
   <field propert="sid" depends="required,sidformat">
    <arg0 key="SID" resource="false"/>
   </field>
  
   <field property="username" depends="required,minlength,maxlength">
    <arg0 key="Username" resource="false"/>
    <arg1 key="${var:minlength}" resource="false"/>
    <arg2 key="${var:maxlength}" resource="false"/>
    <var>
     <var-name>minlength</var-name>
     <var-value>5</var-value>
    </var>
    <var>
     <var-name>maxlength</var-name>
     <var-value>10</var-value>
    </var>
   </field>
  
   <field property="password" depends="required,minlength,maxlength">
    <arg0 key="Password" resource="false"/>
    <arg1 key="${var:minlength}" resource="false"/>
    <arg2 key="${var:maxlength}" resource="false"/>
    <var>
     <var-name>minlength</var-name>
     <var-value>4</var-value>
    </var>
    <var>
     <var-name>maxlength</var-name>
     <var-value>8</var-value>
    </var>
   </field>
  
   <field property="email" depends="required,email">
    <arg0 key="Email ID" resource="false"/>
   </field>
  
   <field property="dob" depends="required,date">
    <arg0 key="DOB" resource="false"/>
    <var>
    <var-name>datePattern</var-name>
    <var-value>dd/MM/yyyy</var-value>
    </var>
   </field>
  
   <field property="phone" depends="required,long">
    <arg0 key="Phone" resource="false"/>
   </field>
  
   <field property="fee" depends="required,double">
    <arg0 key="Fee" resource="false"/>
   </field>
  
   <field property="course" depends="coursesRequired">
   </field>
  </form>
 </formset>
</form-validation>

One file validation-rules.xml when you create struts web framework project through any IDE you will get that file.

Thanks, we hope you will enjoy the tutorial.



5 comments :

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. thank u very much sir....

      Delete
  2. if we extends validaform class in our class .in that class how could you use setter and getter method in above example.and we use setter and getters method same as the developing by using ActionForm

    ReplyDelete