What is Validation in struts:

Validation rules are loosely coupled to the application.
Server-side and client-side validation rules can be defined in one location.


In this example we will see how to do date validation and email validation in struts using validator framework. Our userForm is of type org.apache.struts.validator.DynaValidatorForm. It contains two fields dob and emailId. We use date rule to validate date of birth and email rule to validate email id and age also validate and password and retype password also validating. 

The struts-config.xml file contains the following code to define the userForm.


We use the date rule to validate date. The date rule checks whether the entered date is valid or not. The datePattern variable is used to specify the pattern used by the date.  In this form we use the following date pattern "dd-mm-yyyy". If the datePatternStrict value is "dd-mm-yyyy", then it will accept only dates like 03-21-1986.
Inorder to perform the email validation we use the email rule. We use the required rule to make sure the email id is entered and then we use the email rule to vaidate the email id.like..... ashok@gmail.com

The following messages should be configured in the ApplicationResource.properties file. If an invalid data is entered by the user, then the following values will be used to display the appropriate error messages.
Step 1: index.jsp file using Struts and bean tag library
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<div><html:errors/></div>
<html:form action="/r">
 <table border="2">
        <tr>
           <td><bean:message key="label.uname"/></td>
            <td>Enter Name:<html:text property="uname"/></td>
              </tr><br>
   <tr>
        <td><bean:message key="label.pwd"/></td>
        <td>Enter Password:<html:password property="pwd"/></td>
       
   </tr><br>
    <tr>
       <td><bean:message key="label.rpwd"/></td> 
       <td>Enter ReType Password:<html:password property="rpwd"/></td>
       
   </tr><br>
    <tr>
        <td><bean:message key="label.age"/></td>
        <td>Enter Age:<html:text property="age"/></td>
         </tr><br>
  <tr>
      <td><bean:message key="label.email"/></td>
      <td>  Enter Email-Id:<html:text property="email"/></td>
      
  </tr><br>
   <tr>
      <td><bean:message key="label.dob"/></td>
       <td> Enter Date Of Birth:<html:text property="dob"/>(dd-mm-yyyy)</td>
       </tr><br>
    
   <tr>
       <td><html:submit/></TD>
       <td><bean:message key="label.submit"/></td>
  </TR>
    </table>
</html:form>

Step 2: In message resource file .properties file name is ApplicationResource.properies
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
# -- validator --
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# -- other --
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
# -- welcome --
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It's easy to create Struts applications with NetBeans.
# user label
label.uname=username
label.pwd=password
label.rpwd=retype password
label.age=age
label.email=email
label.dob=date of birth
label.submit=submit
# user errors
error.uname.invalid1=User name is Invalid,It should be a-z,A-Z,0-9,dash "-" or underscore "_" and with letter
error.pwd.required="Password is required<br/>
error.pwd.invalid=Password is Invalid,it should be a-z,A-Z,0-9 and start with Caps Letter

error.rpwd.notmatch=Password and Conform password is Not Matched

Step 3: In validatio.xml file we must configure like this..

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>
    
    <formset>
        <form name="r">
        <field property="uname" depends="required,minlength,maxlength,mask">
            
            <arg key="label.uname"/>
            <arg name="minlength" key="${var.minlength}" resource="false"/>
            <arg name="maxlength" key="${var.maxlength}" resource="false"/>
            <msg name="mask" key="error.uname.invalid1"/>
            <var>
                <var-name>minlength</var-name>
                <var-value>6</var-value>
            </var>
            <var>
                <var-name>maxlength</var-name>
                <var-value>12</var-value>
            </var>
                
            <var>
                <var-name>mask</var-name>
                <var-value>^[a-zA-Z][a-zA-Z0-9-_]*$</var-value>
            </var>
        </field>
        
        <field property="pwd" depends="required,minlength,maxlength,mask">
            
              <arg key="label.pwd"/>
              <arg name="minlength" key="${var.minlength}" resource="false"/>
              <arg name="maxlength" key="${var.maxlength}" resource="false"/>
              
              <var>
                  <var-name>minlength</var-name>
                  <var-value>8</var-value>
                  
                  </var>
                  <var>
                      <var-name>maxlength</var-name>
                      <var-value>16</var-value>
                  </var>
                  
                  <var>
                      <var-name>mask</var-name>
                      <var-value>^[a-zA-Z][a-zA-Z0-9-_]*$</var-value>
                      </var>
        </field>
        
        <field property="rpwd" depends="required,validwhen">
            
            <arg key="label.rpwd"/>
            <msg name="validwhen" key="error.rpwd.notmatch"/>
            <var>
                <var-name>test</var-name>
                <var-value>(pwd==*this*)</var-value>
            </var>
           </field>
           
           <field property="dob" depends="required,date">
               
               <arg key="label.dob"/>
               <var>
                   <var-name>date</var-name>
                   <var-value>dd-mm-yyyy</var-value>
                       
                   </var>
               </field>
               <field property="age" depends="required,integer,intRange">
                   <arg key="label.age"/>
                   <arg name="intRange" key="${var:min}" resource="false"/>
                   <arg name="intRange" key="${var:max}" resource="false"/>
                   <var>
                       <var-name>min</var-name>
                       <var-value>18</var-value>
                           
                  </var>
                       <var>
                       <var-name>max</var-name>
                       <var-value>55</var-value>
                           
                       </var>
                   
               </field>
               
               <field property="email" depends="required,email">
                   <arg key="label.email"/>
                   
               </field>
                     
        </form>
        
        </formset>

<!--
     This is a minimal Validator form file with a couple of examples.
-->

    <global>

        <!-- An example global constant
        <constant>
            <constant-name>postalCode</constant-name>
            <constant-value>^\d{5}\d*$</constant-value>
        </constant>
        end example-->

    </global>

        <!-- An example form -->
      <!--   <formset>
        <form name="logonForm">
            <field
                property="username"
                depends="required">
                    <arg key="logonForm.username"/>
            </field>
            <field
                property="password"
                depends="required,mask">
                    <arg key="logonForm.password"/>
                    <var>
                        <var-name>mask</var-name>
                        <var-value>^[0-9a-zA-Z]*$</var-value>
                    </var>
            </field>
        </form>

    </formset>


</form-validation>

Step 4: Develop a Action class and forwarded to success page RegsiterAction.java

package com.bcns.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class RegsiterAction extends org.apache.struts.action.Action {

    /*
     * forward name="success" path=""
     */
   // private static final String SUCCESS = "success";

  
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        return mapping.findForward("success");
    }
}

Step 5: Configuaring a struts-config.xml file .
Here we are configuring the formbean calss and action class and validator.xml file also as below like...

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">


<struts-config>
    <form-beans>
        <form-bean name="r" type="com.bcns.dto.RegisterFormBean">
     
        </form-bean>
    
    </form-beans>
    
    <global-exceptions>
    
    </global-exceptions>

    <global-forwards>
        <forward name="success" path="/success.jsp"/>
    </global-forwards>

    <action-mappings>
        <action path="/r" type="com.bcns.action.RegsiterAction" name="r" scope="request" validate="true" input="/index.jsp">
             <forward name="success" path="/success.jsp"/>
            </action>
        <action path="/Welcome" forward="/welcomeStruts.jsp"/>
    </action-mappings>
    
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

    <message-resources parameter="com/myapp/struts/ApplicationResource"/>    
    
    <!-- ========================= Tiles plugin ===============================-->
  
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />      
        <set-property property="moduleAware" value="true" />
    </plug-in>
    
    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
  
</struts-config>

Step 6: develop a Formbean class for ..
RegisterFormBean.java and it is extending the ValidatorForm class


package com.bcns.dto;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.validator.ValidatorForm;

public class RegisterFormBean extends ValidatorForm {
    
    String uname=null;
    String pwd=null;
    String rpwd=null;
    String email=null;
    int age;
    String dob=null;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getRpwd() {
        return rpwd;
    }

    public void setRpwd(String rpwd) {
        this.rpwd = rpwd;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }
    
}

step 7: develop a success.jsp file when you are entering valid text..

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<b><font color="red">Hi!&nbsp;<bean:write name="r" property="uname"/></font></b> your entered Details are...<br><br> 

<div>
  
    <table border="1">
 
<tr><td>Age:</td><td><bean:write name="r" property="age"/></td></tr><br>
<tr><td>Email-ID:</td><td><bean:write name="r" property="email"/></td></tr><br>
<tr><td>Date of Birth:</td><td><bean:write name="r" property="dob"/></td></tr><br>
</table>
</div>


    OutPut:

    








Download for Application with jar files  Click Here   (Netbeans Ide)







0 comments:

Post a Comment