Showing posts with label Struts Validator. Show all posts
Showing posts with label Struts Validator. Show all posts

July 14, 2011

Struts 2 - Front-end validation with the Validation Framework

In this code example, we replace the validate() method for basic validation method in the example here with the validation framework.

Front-end validation with the Validation framework lets us configure the validations in a XML file (validation meta-data) and re-use the various, default validators that are provided by the framework.

1) Create the FeedbackForm.jsp and FeedbackDone.jsp files in the WebContent folder of the Web Application

FeedbackForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h4>Enter Feedback</h4>
  <s:form action="PostFeedback">
     <s:textfield name="emailAddress" label="Email Address" />
     <s:textfield name="phoneNumber" label="Phone Number" />
     <s:textarea name="message" label="Message" cols="20" rows="4" />
     <s:submit/>
  </s:form>
</body>
</html>

FeedbackDone.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h3>Your feedback is as follows</h3>
   <s:property value="emailAddress"/><br/>
   <s:property value="phoneNumber"/><br/>
   <s:property value="message"/><br/>
</body>
</html>

2) Create the action class - Feedback.java - in the src folder of the Web Application.

package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class Feedback extends ActionSupport {

   public String execute() { 
      return Action.SUCCESS;
   }
 
   private String emailAddress;
   private String phoneNumber;
   private String message;
 
   public String getEmailAddress() {
      return emailAddress;
   }
   public void setEmailAddress(String emailAddress) {
      this.emailAddress = emailAddress;
   }
 
   public String getPhoneNumber() {
      return phoneNumber;
   }
   public void setPhoneNumber(String phoneNumber) {
      this.phoneNumber = phoneNumber;
   }
 
   public String getMessage() {
      return message;
   }
   public void setMessage(String message) {
      this.message = message;
   }
}

3) Configure the actions in the struts.xml configuration file,

<action name="Feedback" >
   <result>/FeedbackForm.jsp</result>
</action>
  
<action name="PostFeedback" class="info.icontraining.struts2.Feedback">
   <result>/FeedbackDone.jsp</result>
   <result name="input">/FeedbackForm.jsp</result>
</action>

4) Add a new validation framework XML configuration file for the action. This file should be added inside the package where the action class is present along with the properties file. The properties file will prevent the hard-coding of error messages inside the XML configuration file.

The naming convention for the Validation XML file for Struts 2 is ActionClassName-validation.xml
Therefore, create a file, Feedback-validation.xml and add it to the package in which the action class Feedback.java is present

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
   <field name="emailAddress">
      <field-validator type="requiredstring">
         <message>Please enter email address</message>
      </field-validator>
      <field-validator type="email">
         <message key="email.invalid" />
      </field-validator>
   </field>
   <field name="phoneNumber">
      <field-validator type="requiredstring">
         <message>Please enter phone number</message>
      </field-validator>
      <field-validator type="regex">
         <param name="expression"><![CDATA[^(\d){3}-(\d){3}-(\d){4}$]]></param>
         <message key="phone.invalid" />
      </field-validator>
   </field>
   <field name="message">
      <field-validator type="requiredstring">
         <message>Please enter message</message>
      </field-validator>
   </field>
</validators>

5) Add the Feedback.properties tile to the package in which the action class Feedback.java is present

email.invalid=Please enter valid email
phone.invalid=Please enter valid phone (xxx-xxx-xxxx)

6) Access the action by typing the following URL in the browser,

http://localhost:8080/WebAppName/Feedback.action

March 15, 2011

Struts 1.x - Validator Framework Example

We shall replace the validate() method in this example - http://www.javaissues.com/2011/03/struts-1x-reset-and-validate-methods-in.html with the Validator Framework

In addition to the Struts 1.3.8 jars and the Apache Commons jars, also add the Jakarta-Oro jar into the lib folder of your application. Download the oro jar from here

1) Change the LoginForm.java file to make the LoginForm class extend from the ValidatorForm class instead of the ActionForm class. Also remove the validate() method from the LoginForm class.

public class LoginForm extends ValidatorForm {
      ...
}


2) Modify the struts-config.xml file to add the <plug-in> element,

<struts-config>
   ...   
   <message-resources parameter="ApplicationResources" />

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


3) Add a new validation.xml file to the WEB-INF folder of the web application, as below. This configuration will validate the username and password fields for required field validation and also for the form input to comply/match the regular expressions.

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

<form-validation>
 
   <global>
      <constant>
         <constant-name>id</constant-name>
         <constant-value>^([a-zA-Z_]{1}[a-zA-Z0-9_-]{7,14})$</constant-value>
      </constant>
      <constant>
         <constant-name>pass</constant-name>
         <constant-value>^([a-zA-Z0-9_-]{8,15})$</constant-value>
      </constant>
   </global>

   <formset>
      <form name="loginForm">
         <field property="username" depends="required,mask">
            <arg position="0" key="username.required"/>
            <var>
               <var-name>mask</var-name>
               <var-value>${id}</var-value>
            </var>
         </field>
         <field property="password" depends="required,mask">
            <arg position="0" key="password.required"/>
            <msg name="mask" key="password.maskmsg" />
            <var>
               <var-name>mask</var-name>
               <var-value>${pass}</var-value>
            </var>
         </field>
      </form>
   </formset>
 
</form-validation>


4) In the message resources bundle, the ApplicationResources.properties file, add the following messages,

# Struts Validator Error Messages
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.

username.required=Username
password.required=Password
password.maskmsg=Password should be of length between 8 and 15 characters


5) Open the following URL in the browser and test for required field validation as well as form field input validation that complies with the regular expressions in the validation.xml

http://localhost:8080/WebAppName/login.jsp