Creating Custom Validators in STRUTS



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
   

Comments

Popular posts from this blog

Servlets, JSP, Struts and MVC

Hibernate Avg() Function (Aggregate Functions)

Hibernate Count Query