You are on page 1of 67

09/03/2005

Struts Validation Framework, DynaActionForm

In this presentation, we are going to talk about advanced features of Struts. I expect the audience of this presentation has some basic understanding on Struts.

09/03/2005

Sang Shin
sang.shin@sun.com www.javapassion.com Java Technology Evangelist Sun Microsystems, Inc.
2

09/03/2005

Disclaimer & Acknowledgments


?

Even though Sang Shin is a full-time employee of Sun Microsystems, the content in this presentation is created as his own personal endeavor and thus does not reflect any official stance of Sun Microsystems. Sun Microsystems is not responsible for any inaccuracies in the contents. Acknowledgments:

Struts' user's guide is also used in creating slides and speaker notes

09/03/2005

Revision History
? ? ?

12/01/2003: version 1: created by Sang Shin 04/09/2004: version 2: speaker notes are polished a bit 09/01/2005: Strutsframework slides are separated out from advanced struts Things to do speaker notes need to be added more example codes need to be added javascript slides need to be added

09/03/2005

Topics
? ?

DynaActionForm Validation Framework

How to configure and use validation framework

validations-rules.xml validations.xml How to use DynaActionForm with validation framework Client side validation with JavaScript I18N and validation Custom validation
5

09/03/2005

DynaActionForm (Introduced in 1.1)


6

Now let's move on to the next topic, DynaActionForm.

09/03/2005

Why DynaActionForm?
?

Issues with using ActionForm


ActionForm class has to be created in Java programming language For each HTML form page, a new ActionForm class has to be created Every time HTML form page is modified (a property is added or removed), ActionForm class has to be modified and recompiled

DynaActionForm support is added to Struts 1.1 to address these issues


7

Now let's talk about why having DynaActionForm would be useful. Maintaining a separate concrete ActionForm class for each form in your Struts application is time-consuming. It is particularly frustrating when all the ActionForm does is gather and validate simple properties that are passed along to a business JavaBean. This bottleneck can be alleviated through the use of DynaActionForm classes. Instead of creating a new ActionForm subclass and new get/set methods for each of your bean's properties, you can list its properties, type, and defaults in the Struts configuration file.

09/03/2005

What is DynaActionForm?
?

org.apache.struts.action.DynaActionForm

extends ActionForm class Properties are configured in configuration file rather than coding reset() method resets all the properties back to their initial values You can still subclass DynaActionForm to override reset() and/or validate() methods
?

In DynaActionForm scheme,

Version exists that works with Validator framework to provide automatic validation
8

So what is DynaActionForm? DynaActionForm class extends ActionForm class. But this class is created by the framework not by you. Under DynaActionForm scheme, properties are configured in configuration file rather than you manually code ActionForm class. The reset() method resets all the properties back o their initial values. You can still subclass DynaActionForm in order to override reset and/or validate() methods. Now as we will see in the Validator Framework later on, there is a version of DynaActionForm, in fact a subclass of DynaActionForm, which is called DynaValidatorActionForm.

09/03/2005

How to Configure DynaActionForm?


?

Configure the properties and their types in your struts-config.xml file

add one or more <form-property> elements for each <form-bean> element

Now let's see how we can configure DynaActionForm? Basically you configure properties and their types in the struts-config.xml file with <form-property> element for each property for each <form-bean> element, which represents a form bean.

09/03/2005

Example from struts-examples


<form-beans> <!-- Simple ActionForm Bean --> <form-bean name="simpleForm" type="examples.simple.SimpleActionForm"/> <!-- DynaActionForm Bean --> <form-bean name="dynaForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="name" type="java.lang.String" /> <form-property name="secret" type="java.lang.String" /> <form-property name="color" type="java.lang.String" /> <form-property name="confirm" type="java.lang.Boolean" /> <form-property name="rating" type="java.lang.String" /> <form-property name="message" type="java.lang.String" /> <form-property name="hidden" type="java.lang.String" /> </form-bean> </form-beans>
10

So this is the fragment of struts-config.xml file from struts-examplesSteve sample code. Here the <form-beans> element has two <form-bean> elements, each of which represent a form bean. The first form bean is called as simpleForm and it is a regular ActionForm. The second form bean is called dynaForm and it is the type of DynaActionForm. Here you specify each property of the bean by <formproperty> element with name and type attributes. So instead of you write ActionForm class with various getter and setter methods, you specify them in the configuration file. And it is the framework's responsibility to create DynaActionForm object from this configuration.

10

09/03/2005

Types Supported by DynaActionForm


? ? ? ? ? ? ? ? ? ? ?

java.lang.BigDecimal, java.lang.BigInteger boolean and java.lang.Boolean byte and java.lang.Byte char and java.lang.Character java.lang.Class, double and java.lang.Double float and java.lang.Float int and java.lang.Integer long and java.lang.Long short and java.lang.Short java.lang.String java.sql.Date, java.sql.Time, java.sql.Timestamp

11

This slide lists types supported by DynaActionForm. You may also specify Arrays of these types (e.g. String[]). You may also specify a concrete implementation of the Map Interface, such as java.util.HashMap, or a List implementation, such as java.util.ArrayList. If you do not supply an initial attribute, numbers will be initialized to 0 and objects to null.

11

09/03/2005

Example from struts-submit sample application


public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Retrieve the value of lastname field String lastName = (String)((DynaActionForm)form).get("lastName"); ....

12

We will talk about Validator framework in detail in the following section. But I just want to give you a sense on how validation can be performed. Basically you use DynaValidatorForm class as shown in this slide. This way, form validation is also specified in the configuration file.

12

09/03/2005

How to perform Validation with DynaActionForm?


?

DynaActionForm does not provide default behavior for validate() method

You can subclass and override validate() method but it is not recommended Use DynaValidatorForm class (instead of DynaActionForm class) DynaValidatorForm class extends DynaActionForm and provides basic field validation based on an XML file
13

Use Validator Framework


So how do you perform form validation with DynaActioForm? Because DynaActionForm itself does not provide default behavior for validate() method, you can subclass the DynaActionForm class then provide your own validate() method, but it is a recommended approach. Instead, using Validator framework is recommended.

13

09/03/2005

Example from strut-example sample application


<form-beans> <!-- Logon form bean --> <form-bean name="logonForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> <!-- Subscription form bean --> <form-bean name="subscriptionForm" type="org.apache.struts.webapp.example.SubscriptionForm"/> </form-beans>
14

We will talk about Validator framework in detail in the following section. But I just want to give you a sense on how validation can be performed. Basically you use DynaValidatorForm class as shown in this slide. This way, form validation is also specified in the configuration file.

14

09/03/2005

Validation Framework (added to Struts 1.1 Core)

15

So let's talk about Validator framework.

15

09/03/2005

Why Struts Validation Framework?


?

Issues with writing validate() method in ActionForm classes


You have to write validate() method for each ActionForm class, which results in redundant code Changing validation logic requires recompiling

Struts validation framework addresses these issues

Validation logic is configured using built-in validation rules as opposed to writing it in Java code
16

Let's talk about the motivation for Validator framework. In Struts 1.0 where there is no validator framework, in order to perform form validation, you have to write validate() method in each ActionForm. Now the problems of this approach is twofold. First, since you have to write validate() method for every ActionForm class, and most of these ActionForm's have somewhat similar validation logic, there will be redundant code. Second, if you need to change the validation logic, you have to modify the Java code and then recompile it. Struts validation framework addresses these issues. That is, in Validator framework, validation logic an be configured instead of writing it as a Java code.

16

09/03/2005

What is Struts Validation Framework?


?

Originated from generic Validator framework from Jakarta Struts 1.1 includes this by default

Allows declarative validation for many fields Formats


?

Dates, Numbers, Email, Credit Card, Postal Codes Minimum, maximum

Lengths
?

Ranges
17

So what is the Struts Validation framework? It is originated from generic validator framework, which was developed as a open source project in Jakarta. The Struts 1.1 includes the validation framework as part of the framework. So the validation framework allows declarative validation for many fields. The formats of the fields can be date, number, email, credit cared, or postal code. Or it could be checked against minimum or maximum length of the field. Also range can be also specified.

17

09/03/2005

Validation Rules
? ?

Rules are tied to specific fields in a form Basic Validation Rules are built-in in the Struts 1.1 core distribution

e.g. required, minLength, maxLength, etc.

The built-in validation rules come with Javascript that allows you to do client side validation Custom Validation rules can be created and added to the definition file.

Can also define regular expressions


18

18

09/03/2005

Validation Framework: How to configure and use Validation framework?


19

So how do you configure and use Struts validation framework?

19

09/03/2005

Things to do in order to use Validator framework


? ?

? ?

Configure Validator Plug-in Configure validation.xml file (and validationrules.xml file) Extend Validator ActionForms or Dynamic ActionForms Set validate=true on Action Mappings Include the <html:javascript> tag for client side validation in the form's JSP page
20

So this slide lists the things you have to do in order to use Struts validator framework. First, you want to configure validator plugin. Next, you want to write and configure validation.xml file. Since validation-rules.xml is provided by the Struts framework itself, you don't have to write it yourself. Then extend either validator ActionForm or DynamicActionForm's. And then set the validate attribute to true in Action mapping. Also if you want to use client side validation using Javascropt, include <html:javascript> tag. So let's go over each of these steps in a bit more detail.

20

09/03/2005

How to Configure Validator Plugin


?

Validator Plug-in should be configured in the Struts configuration file

Just add the following <plug-in> element

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

21

The validator plugin should be configured in struts-config.xml file. Configuing the validator plugin is rather easy as shown above.

21

09/03/2005

Two Validator Configuration Files


?

validation-rules.xml

Contains global set of validation rules Provided by Struts framework Application specific Provided by application developer It specifies which validation rules from validationrules.xml file are used by a particular ActionForm No need to write validate() code in ActionForm class
22

validation.xml

The next thing you have to do is to write and configure two validation related configuration files - validation-rules.xml and validation.xml file. The validation-rules.xml contains global set of validation rules and is provided by the Struts framework itself. The validation.xml file is per application specific and is provided by application developer. That is, this is the file you, as a Struts application developer, have to be concerned about. The validation.xml file specifies which validation rules from validation-rules.xml file are used by a particular ActionForm. Now as you can see, in validation framework, you specify the validation rules in a configuration file as opposed to writing validate (0 method in Java programming language.

22

09/03/2005

Validation Framework:

validation-rules.xml
23

Now let's talk about validation-rules.xml file. As was mentioned before, this file is provided by the Struts framework itself and you don't usually change this file.

23

09/03/2005

Built-in (basic) Validation Rules


? ? ? ? ? ? ?

required, requiredif minlength maxlength mask byte, short, integer, long, float, double date, range, intRange, floatRange creditCard, email

24

This slide lists built-in validation rules. That is the validation rules of required, minlength, or maxlength are already specified in the validationrules.xml file. So let's see the contents of validation-rules.xml file in the following two slides.

24

09/03/2005

validation-rules.xml: Built-in required validation rule


<form-validation> <global> <validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required"> <javascript><![CDATA[ function validateRequired(form) { var isValid = true; ... </javascript> </validator> 25

This slide shows fragment of the validation-rules.xml file that specifies the validation rule of required.

25

09/03/2005

validation-rules.xml: Built-in minlength validation rule


<validator name="minlength" classname="org.apache.struts.validator.FieldChecks" method="validateMinLength" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" depends="" msg="errors.minlength"> <javascript><![CDATA[ function validateMinLength(form) { var isValid = true; var focusField = null; ... </javascript> </validator> 26

This slide shows the validation rule of minlength.

26

09/03/2005

Attributes of <validator ...> Element


? ?

name: logical name of the validation rule classname, method: class and method that contains the validation logic methodParams: comma-delimited list of parameters for the method msg: key from the resource bundle

Validator framework uses this to look up a message from Struts resource bundle

depends: other validation rules that should be called first


27

Just to summarize what I said in the previous two slides, here is the description of each attribute of <validator> element. Again, since validation-rules.xml file is provided by Struts framework itself, you do not have to write this yourself. So the name attribute specifies the logical name of the validation rule. This name will be used in validation.xml file. The classname and method attributes specify the class and method that contain the validation logic. Again, Struts already provide this class and methods. The methodParams is a commadelimited list of parameters that are passed to the method. The msg attribute specifies the key from the resouce bundle. Validator framework uses this key value to lookup a message from Struts resource bundle. Finally the depends attrubute specifies other validation rules that should be called first before the current one gets called.

27

09/03/2005

Built-in Error Messages From Validator Framework


# Built-in error messages for validator framework checks # You have to add the following to your application's resource bundle errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {2} characters. errors.invalid={0} is invalid. errors.byte={0} must be an byte. errors.short={0} must be an short. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.float={0} must be an float. errors.double={0} must be an double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address.
28

Validator framework has defined a set of error messages that can be used for error messages. These error messages need to be copied into your application's resource file. Please note {0}, {1}, {2} indicates the parameter location where passed-in paramters will be placed. These parameters are specified with <arg0>, <arg1>, and <arg2> elements in the validation.xml file which we will see in the following slide.

28

09/03/2005

Validation Framework:

validation.xml
29

Now let's talk about validation.xml file that you have to provide.

29

09/03/2005

validation.xml: logonForm (from struts-examples sample code)


<form-validation> <!-- ========== Default Language Form Definitions ===================== --> <formset> <form name="logonForm"> <field property="username" depends="required, minlength,maxlength"> <arg0 key="prompt.username"/> <arg1 key="${var:minlength}" name="minlength" resource="false"/> <arg2 key="${var:maxlength}" name="maxlength" resource="false"/> <var> <var-name>maxlength</var-name> <var-value>16</var-value> </var> <var> <var-name>minlength</var-name> <var-value>3</var-value> </var> </field>

30

This is the validation.xml file from struts-examples1 sample code. In this page, we have a form named as loginForm. This form has two properties, username and password. In this slide, what you see is the validation rule that is applied to the username property. In this example, the validation rule of the username property says that it is required, and there are minimum and maximum length constraints. Because it is required property, an end user has to enter some value to the field. Otherwise, some error indication will be returned to the user. The length of the username has to be minimum 3 characters and maximum 16 characters. The <arg0>, <arg1>, and <arg2> elements specify parameters that will passed to the error message that gets displayed to the user.

30

09/03/2005

validation.xml: logonForm (from struts-examples sample code)


<field property="password" depends="required, minlength,maxlength" bundle="alternate"> <arg0 key="prompt.password"/> <arg1 key="${var:minlength}" name="minlength" resource="false"/> <arg2 key="${var:maxlength}" name="maxlength" resource="false"/> <var> <var-name>maxlength</var-name> <var-value>16</var-value> </var> <var> <var-name>minlength</var-name> <var-value>3</var-value> </var> </field> </form>

31

This slide shows the validation rule that is applied to the password property.

31

09/03/2005

validation.xml: registrationForm (from struts-examples sample code)


<form name="registrationForm"> <field property="fromAddress" depends="required,email"> <arg0 key="prompt.fromAddress"/> </field> <field property="fullName" depends="required"> <arg0 key="prompt.fullName"/> </field> <field property="replyToAddress" depends="email"> <arg0 key="prompt.replyToAddress"/> </field> <field property="username" depends="required"> <arg0 key="prompt.username"/> </field> </form> </formset> </form-validation> 32

This slide shows the validation rule that gets applied to the fields of the registrationForm. For example, the formAddress field is required and it has to be the format of email.

32

09/03/2005

<form ...> Element


?

Defines a set of fields to be validated

<!ELEMENT form (field+)> Name attribute: Corresponds name attribute of <form-bean> in struts-config.xml

Attributes

33

Now hopefully by now, you get some sense of how validation rules can be specified through <form-bean> element and its child <field> elements in the struts-config.xml file through the examples we saw in the previous slides. Let's go over each element just to make sure we have a clear understanding. First, the <form> element. The <form> element can have one or more <field> elements. It also can have name attribute, the value of which should correspond to the value of name attribute of the <form-bean> as we will see in the following slide.

33

09/03/2005

struts-config.xml: logonForm (from struts-examples sample code)


<form-beans> <!-- Logon form bean --> <form-bean name="logonForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> <!-- Subscription form bean --> <form-bean name="subscriptionForm" type="org.apache.struts.webapp.example.SubscriptionForm"/> </form-beans>

34

This slide shows the <form-bean> element of the logonForm in the strutsconfig.xml. As was mentioned in the previous slide, the value of the name attribute of the <form-bean> element in the struts-config.xml file, logonForm in this example, matches the value of name attribute in the<form> element in the validation.xml file.

34

09/03/2005

<field ...> Element


?

Corresponds to a property in an ActionForm

<!ELEMENT field (msg?, arg0?, arg1?, arg2?, arg3?, var*)> property: name of a property (in an ActionForm) that is to be validated depends: comma-delimited list of validation rules to apply against this field
?

Attributes

All validation rules have to succeed

35

The <field> element corresponds to a property in an ActionForm class. The syntaxt of the <field> element says it can have optional <msg> child element, optional <arg0> child element, optional, <arg1> child element, optional <arg2> child element, optional <arg3> child element, and zero or more <var> child elements. It can also have property and depends attributes. The property attribute specifies the name of the property that needs to be validatd and the depends attribute specifies comma-delimited list of validation rules that need to be applied to the field. Of course, all the validation rules need to be successful in order to have a successful validation.

35

09/03/2005

<field ...> Element: <msg ...> child element


?

Allows you to specify an alternate message for a field element <msg name=.. key=... resource=.../>

name: specifies rule with which the msg is used, should be one of the rules in validation-rules.xml key: specifies key from the resource bundle that should be added to the ActionError if validation fails resource: if set to false, the value of key is taken as literal string

36

OK. We talked a bit on <field> element. Now let's talk about the child elements of <field> element. The <msg> child element allows you to specify an alternate message for a field element. And it can have three possible attributes. The name attribute specifies rule with which the msg is used and it should be one of the rules in the validation-rules.xml file. The key attribute specifies a key from the resource bundle that should be adde to the ActionError if validation fails. The resource attribute is, if set to false, indicates that the value of the key is taken as a liternal string rather than a key to the resource bundle.

36

09/03/2005

<field ...> Element: <arg0 ...> child element


?

<arg0 key=.. name=.. resource=..>


Are used to pass additional values to the message <arg0> is the 1 st replacement and <arg1> is the 2nd replacement, and so on

37

The <arg0> (and <arg1>, <arg2>, <arg3>) child elements are used to pass additional values to the message. That is, <arg0> is the 1st parameter and <arg1> is the 2nd parameter to the message.

37

09/03/2005

<field ...> Element: <var ...> child element


<var> <var-name>...</var-name> <var-value>...</var-value> </var> ? Set parameters that a field element may need to pass to one of its validation rules such as minimum and miximum values in a range validation ? Referenced by <argx> elements using ${var: var-name} syntax
38

The <var> child element set parameters that a field element may need to pass to one of its validation rules such as minimum or maximum values in a range validation. And it is referenced by <argx> elements using ${var:var-name} syntax.

38

09/03/2005

Validation Framework:

How do you use ActionForm with Validator?


So how do you use ActionForms with Validator?

39

39

09/03/2005

ActionForm and Validator


?

You cannot use ActionForm class with the Validator

Instead you need to use special subclasses of ActionForm class

Validator supports two types special ActionForms

Standard ActionForms
? ?

ValidatorActionForm ValidatorForm DynaValidatorActionForm DynaValidatorForm

Dynamic ActionForms
? ?

40

If you want to use Validator with ActionForm, you cannot use ActionForm in their vanilla form. Instead you need to use special subclass of ActionForm class. Validator framework supports two types of special ActionForms - one that is based on Stadnard ActionForms and the other based on dynamic ActionForms. The former include ValidatorActionForm and ValidatorForm. And the latter includes DynaValidatorActionForm and DynaValidatorForm.

40

09/03/2005

Choices You have


?

Standard ActionForms or Dynamic ActionForms? (rehash)

If you want to specify ActionForms declaratively, use dynamic ActionForms Use xValidatorActionForm if you want more finegrained control over which validation rules are executed In general, xValidatorForm should be sufficient

xValidatorActionForm or xValidatorForm?

41

So the choices you have to make is whether you want to use standard ActionForms or Dynamic ActionForms. As we learned in the beginning of this presentation, if you want to specify ActionForms in declarative fashion, then you want to use Dynamic ActionForms. The next decision you have to make is whether you want to use ValidatorActionForm or ValidatorForm if you are using standard ActionForms or whether you want to use DynaValidateActionForm or DynaValidatorForm if uou are using Dynamic ActionForms. Usually using xValidatorForm should be sufficient.

41

09/03/2005

Validation Framework:
struts-example Sample code
42

Now I would like to use struts-example1 sample code to go over various pieces that are relevant to validator framework.

42

09/03/2005

struts-config.xml: DynaValidatorForm
<!-- ========== Form Bean Definitions === --> <form-beans> <!-- Logon form bean --> <form-bean name="logonForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> <!-- Subscription form bean --> <form-bean name="subscriptionForm" type="org.apache.struts.webapp.example.SubscriptionForm"/> </form-beans>
43

This slide shows the <form-bean> element which has logonForm as the value of name attribute and org.apache.struts.validator.DynaValidatorForm class as the value of type attribute. What this means is that the ActionForm called logonForm uses DynaValidatorForm as a validator. Please note that this class is provided by the Struts framework itself not you.

43

09/03/2005

validation-rules.xml: Built-in required validation rule


<form-validation> <global> <validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required "> <javascript><![CDATA[ function validateRequired(form) { var isValid = true; ... </javascript> </validator> 44

This is the same required validation rule we have seen before. I added it here for the sake of completeness of this example.

44

09/03/2005

validation-rules.xml: Built-in minlength validation rule


<validator name="minlength" classname="org.apache.struts.validator.FieldChecks" method="validateMinLength" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" depends="" msg="errors.minlength" > <javascript><![CDATA[ function validateMinLength(form) { var isValid = true; var focusField = null; ... </javascript> </validator> 45

This is the same minlength validation rule we have seen before. I've added it here for the sake of completeness of this example.

45

09/03/2005

validation.xml: logonForm
<form-validation> <!-- ========== Default Language Form Definitions ===================== --> <formset> <form name="logonForm"> <field property="username" depends="required, minlength,maxlength"> <arg0 key="prompt.username"/> <arg1 key="${var:minlength}" name="minlength" resource="false"/> <arg2 key="${var:maxlength}" name="maxlength" resource="false"/> <var> <var-name>maxlength</var-name> <var-value>16</var-value> </var> <var> <var-name>minlength</var-name> <var-value>3</var-value> </var> </field>

46

This is the same validation.xml file of struts-example sample code we've seen before. I added it here for the sake of completeness of the example.

46

09/03/2005

ApplicationResources.Properties
# Standard error messages for validator framework checks errors.required={0} is required. errors.minlength={0} cannot be less than {1} characters. errors.maxlength={0} cannot be greater than {2} characters. errors.invalid={0} is invalid. errors.byte={0} must be an byte. errors.short={0} must be an short. errors.integer={0} must be an integer. errors.long={0} must be an long. errors.float={0} must be an float. errors.double={0} must be an double. errors.date={0} is not a date. errors.range={0} is not in the range {1} through {2}. errors.creditcard={0} is not a valid credit card number. errors.email={0} is an invalid e-mail address.

47

This is the ApplicationResources.properties file that contains the error messages. Again, we have seen this before.

47

09/03/2005

LogonForm Validation: required

48

This picture shows LogonForm validation. Here I entered only username. Since both username and password fields are required ones, I get the error message. By the way, since the required built-in validation rule is performed via client side JavaScript, you see a reference to JavaScript in the error message pop up box.

48

09/03/2005

LogonForm Validation: minlength

49

This is the same logonForm validation. This time, I entered just one single chracter username and password. Since both fields are associated with minlength and maxlength validation rules, the error message dialog box is popped up.

49

09/03/2005

LogonForm Validation: maxlength

50

This time, I entered very long username and get error message indicating that the number of characters exceeded the maxlength.

50

09/03/2005

struts-config.xml: Regular ActionForm class (actually extension of it)


<!-- ========== Form Bean Definitions === --> <form-beans> <!-- Logon form bean --> <form-bean name="logonForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="username" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> <!-- Subscription form bean --> <form-bean name="subscriptionForm" type="org.apache.struts.webapp.example.SubscriptionForm"/> </form-beans>
51

This slide is the same struts-config.xml that we saw but this time we will see regular ActionForm class, actually an extension of ActionForm class, subscriptionForm class.

51

09/03/2005

SubscriptionForm class
public final class SubscriptionForm extends ActionForm { ... public String getAction() { return (this.action); } public void setAction(String action) { this.action = action; } ... public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ... } ... }
52

So as you can see in this slide, this is old way of doing things - we code ActionForm class and then we do code validate() method.

52

09/03/2005

Validation Framework:
How to perform Client-side Validation using JavaScript?
53

Now let's talk about how to perform client-side validation using JavaScript.

53

09/03/2005

JavaScript Support in Validator Framework


?

The Validator framework is also capable of generating JavaScript for your Struts application using the same framework as for server-side validation

By using a set of JSP custom tags designed specifically for this purpose

54

54

09/03/2005

Configuring validation-rules.xml for JavaScript


?

A custom tag is used to generate client-side validation based on a javascript attribute being present within the <validator> element in the validation-rules.xml file Use the custom tag in your JSP page

The text from <javascript> element is written to the JSP page to provide client-side validation

55

55

09/03/2005

Configuring validation-rules.xml for JavaScript


<form-validation> <global> <validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" m sg="errors.required"> <javascript><![CDATA[ function validateRequired(form) { var isValid = true; ... </javascript> </validator> 56

This is the same required validation rule we have seen before. I added it here for the sake of completeness of this example.

56

09/03/2005

Validation Rules for the logonForm in validation.xml


<form name="logonForm"> <field property="username" depends="required, minlength,maxlength"> <arg0 key="prompt.username"/> <arg1 key="${var:minlength}" name="minlength" resource="false"/> <arg2 key="${var:maxlength}" name="maxlength" resource="false"/> ... </field> <field property="password" depends="required, minlength,maxlength" bundle="alternate"> ...
57

57

09/03/2005

Things You Have to Do in your JSP Page


?

You will need to include the <html:javascript> tag with the name of the ActionForm that it's going to validate against The formName attribute is used to look up the set of validation rules to include as JavaScript in the page

58

58

09/03/2005

logon.jsp Page (from strutsexample sample code)


<html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="false"/> <script language="Javascript1.1" src="staticJavascript.jsp"> </script>

59

59

09/03/2005

Things You Have to Do in your JSP Page


?

You will have to add an onsubmit event handler for the form manually When the form is submitted, the validateLogonForm( ) JavaScript function will be invoked

The validation rules will be executed, and if one or more rules fail, the form will not be submitted.

60

60

09/03/2005

Things You Have to Do in your JSP Page


?

The <html:javascript> tag generates a function with the name validateXXX( ) , where XXX is the name of the ActionForm

Thus, if your ActionForm is called logonForm, the javascript tag will create a JavaScript function called validateLogonForm( ) that executes the validation logic This is why the onsubmit( ) event handler called the validateLogonForm( ) function.

61

61

09/03/2005

logon.jsp Page (from strutsexample sample code)


<html:form action="/logon" focus="username" onsubmit="return validateLogonForm(this);"> <table border="0" width="100%"> <tr> <th align="right"> <bean:message key="prompt.username"/>: </th> <td align="left"> <html:text property="username" size="16" maxlength="18"/> </td> </tr> ... </html>
62

62

09/03/2005

Validation Framework:
I18N and Validation
63

63

09/03/2005

I18N and Validator


?

Validator framework uses Struts resource bundle <formset> element in validation.xml supports language, country, variant
<formset> ... </formset> <formset language=fr> ... </formset> <formset language=fr country=CA> ... </formset>

64

64

09/03/2005

Validation Framework:
Advanced Features of Validator
65

Validation framework provides more advanced features. In this presentation, we will just them but I encourage folks to try these advanced features on their own.

65

09/03/2005

Advanced Features
? ?

Creating custom validators Using programmatic validation along with Validator

66

So you can build and deploy your own custom validators. You can also use both programmatic validation along with Validator framework. You can also use Validator framework without Struts.

66

09/03/2005

Passion!
67

67

You might also like