Services | Updates | Contact
Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
Data Definition Statement
In this section we will describe you the syntax of most of the Data Definition statements supported by MySQL.
 
Linux Basics
Linux is a free open source operating system based on Unix, which runs on varieties of hardware platforms.
 
More Tutorials...


    Loan Information     Struts     Open Source

Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML

 
 
Struts

 
Comments
 
 

 

Creating Custom Validators in STRUTS

                         

Author: Murthy Gandikota (murthy64@hotmail.com)

In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

The client-side validation in Struts is well known. Here are some of the available features:

  • required
  • requiredif
  • validwhen
  • minlength
  • maxlength
  • mask
  • byte
  • short
  • integer
  • long
  • float
  • double
  • byteLocale
  • shortLocale
  • integerLocale
  • longLocale
  • floatLocale
  • doubleLocale
  • date
  • intRange
  • longRange
  • floatRange
  • doubleRange
  • creditCard
  • email
  • url

These are found in the validator-rules.xml inside the <validator> tags. The validator-rules.xml file is found in the commons-validator jar.

Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the <global> tag:

        <validator name="matchname"
                   classname="org.apache.struts.validator.FieldChecks"
                   method="validateName"
                   methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
                   msg="errors.name">
        <javascript><![CDATA[
                function validateName(form) {
        var isValid = true;
        var focusField = null;
        var i = 0;
        var fields = new Array();

        var omatchName= eval('new ' + jcv_retrieveFormName(form) +  '_matchname() ');

        for (var x in omatchName) {
            if (!jcv_verifyArrayElement(x, omatchName[x])) {
                continue;
            }
            var field = form[omatchName[x][0]];

            if (!jcv_isFieldPresent(field)) {
                fields[i++] = omatchName[x][1];
                isValid=false;
                } else if (field.value != "administrator") {
                        fields[i++]=omatchName[x][1];
                        isValid=false;
                }
        }
        
        if (fields.length > 0) {
           jcv_handleErrors(fields, focusField);
        }
        return isValid;
        }
        ]]>
        </javascript>
        </validator>

To understand the above code:

  • matchname is the new validator we are creating; use can use anything you want (e.g. matchAdmin) remembering that this will be used in another file which will be described later
  • the error message issued in the browser has the key errors.name; you can have any name here like errors.admin; once again this will be explained later
  • the Java Script function to call is declared in the method attribute of the validator tag; in the above it is called validateName; you can have any valid Java Script function name (e.g. validateAdmin)
  • the Java Script to process this tag is declared inside CDATA; note that the function name should match EXACTLY with the name declared in the method attribute of the validator tag
  • the field.value != "administrator" is where we actually test the value entered in the browser; you can substitute any string in the place of "administrator"; also you can do more sophisticated checking (e.g. replace all blanks; check for upper/lower case, etc.) if you are an experienced Java Script programmer

To use our matchname validator create a file validation.xml and add the following lines:

<!-- Name form Validation-->
<form-validation>
<formset>
<form name="AdminForm">
    <field  property="name"
          depends="matchname">
         <arg0 key="AddressForm.name"/>
    </field>
</form>
</formset>
</form-validation>

Copy the files validation.xml and validator-rules.xml to the directory where your struts-config.xml resides. Let us say it is WEB-INF. Next we have to create the error message for errors.name. Create a directory WEB-INF/resources and a file in this directory with the name application.properties. Add the following lines to application.properties

AdminForm.name=Name
errors.name={0} should be administrator.
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.

Edit struts-configuration.xml and add the following lines

<form-bean name="AdminForm" type="test.AdminForm"/>

<action
     path="/AdminFormValidation"
     type="test.AdminForm"
     name="AdminForm"
     scope="request"
     validate="true"
     input="admin.jsp">
     <forward name="success" path="success.jsp"/>
</action>


<message-resources parameter="resources/application"/>

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

Create a JSP file as follows:


<%@ taglib uri="struts-bean.tld" prefix="bean" %>
<%@ taglib uri="struts-html.tld" prefix="html" %>

<html:html>
<head>
    <title>Administrator Test</title>
<html:base/>
</head>
<body bgcolor="white">
<html:form action="/AdminFormValidation" method="post" onsubmit="return validateAdminForm(this);">

<div align="left">
<p>
This application shows the use of Struts Validator.<br>
The following form contains fields that are processed by Struts Validator.<br>
Fill in the form and see how JavaScript generated by Validator Framework validates the form.
</p>

<p>
<html:errors/>
</p>
<table>

<tr>
<td align="right">
<b>Name</b>
</td>
<td align="left">
<html:text property="name" size="30" maxlength="30"/>
</td>
</tr>
<tr>
<td align="right">
<html:submit>Save</html:submit>
</td>
<td align="left">
<html:cancel>Cancel</html:cancel>
</td>
</tr>
</table>
</div>

<!-- Begin Validator Javascript Function-->
<html:javascript formName="AddressForm"/>
<!-- End of Validator Javascript Function-->

</html:form>
</body>
</html:html>

Then we create the success.jsp


<% out.println("SUCCESS") %>

Then we create the Java Class for the AdminForm

package test;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;


/**
 * Form bean for the Admin Entry Screen.
 *
*/
public class AdminForm extends ActionForm
{
  private String name=null;
 
  public void setName(String name){
    this.name=name;
  }

  public String getName(){
    return this.name;
  }


    /**
     * Reset all properties to their default values.
     *
     * @param mapping The mapping used to select this instance
     * @param request The servlet request we are processing
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    this.name=null;
    }

    /**
     * Reset all properties to their default values.
     *
     * @param mapping The mapping used to select this instance
     * @param request The servlet request we are processing
   * @return errors
     */
  public ActionErrors validate(
      ActionMapping mapping, HttpServletRequest request ) {
      ActionErrors errors = new ActionErrors();

      if( getName() == null || getName().length() < 1 ) {
        errors.add("name",new ActionMessage("error.name.required"));
      }
      }

      return errors;
  }

}

Create the AdminAction.java


package test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

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

Finally compile the classes and restart the web server and view the AdminForm.jsp

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

5 comments so far (post your own) View All Comments Latest 10 Comments:

I think mariusz is correct.
It should be type="test.AdminAction"
whereas he wrote:
<action
path="/AdminFormValidation"
type="test.AdminForm"
name="AdminForm"
scope="request"
validate="true"
input="admin.jsp">
<forward name="success" path="success.jsp"/>
</action>

Posted by Sandeep on Thursday, 04.3.08 @ 01:36am | #55152

hi sir your material is very help ful thanks

Posted by suresh on Monday, 02.11.08 @ 12:53pm | #47892


There is no word to express your hard work..


"Every duty is holy and devotion to duty is the
highest form of worship of god."

-swami vivekanada.

Posted by Pandi Palanichamy on Friday, 01.11.08 @ 10:55am | #44962

o think you made mistake:
Should it be type="test.AdminAction"
<action
path="/AdminFormValidation"
type="test.AdminForm"
name="AdminForm"
scope="request"
validate="true"
input="admin.jsp">
<forward name="success" path="success.jsp"/>
</action>

Posted by mariusz on Friday, 11.2.07 @ 01:30am | #35358

Hi,
I have been using Eclipse3.2 and Struts 1.3.5. From the tutorial "Creating Custom Validators", I was a bit confused with finding the location of validator-rules.xml file. At last, I found it under struts-core-1.3.5.jar. You can either import struts-blank-1.3.5.jar into your project or just include the struts-core-1.3.5.jar in Java Build path. This will include the above mentioned file and then you can start editing it to define your custom defined validators. Happy coding !!

Posted by Srinivas Marripudi on Thursday, 10.4.07 @ 16:27pm | #31366

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.