Validation Framework in Struts
- Overview of validation framework
- Configuration Files
- Configuring validation-rules.xml and
- Configuring validation.xml
- Using an ActionForm with the validator
- Plug the validator with struts
- Example for Validation
Overview of Validation Framework |
- The Validator framework allows us to move all the validation logic completely outside of the ActionForm and declaratively configure it for an application through external XML files.
- No validation logic is necessary in the ActionForm, which makes your application easier to develop and maintain.
- Another benefit of the Validator is that it is very extensible.
- It provides many standard validation routines out of the box, but if you require additional validation rules, the framework is easy to extend and provides the ability to plug in your own rules (again without needing to modify your application).
Advantage of using Validation Framework
Validation framework is used to overcome the problems, which occurred while using the validation logic in ActionForm.
Problem 1:
- Redundant validation logic throughout your application.
- Even if you use a single ActionForm for our entire application, you might still end up duplicating the validation logic for the various properties.
Problem 2:
- Maintenance.
- If you need to modify or enhance the validation that occurs for an ActionForm, then the source code must be recompiled.
- The Validator depends on several other packages to function properly, and the most important of these is the Jakarta ORO package.
- The ORO package contains functionality for regular expressions, performing substitutions, and text splitting, among other utilities.
- Other packages required by the Validator are Commons BeansUtils, Commons Logging, Commons Collections, and Digester.
- The JAR that needs to be placed is commons-validator.jar jakarta-oro.jar
Configuration Files |
- The Validator framework allows the validation rules for an application to be declaratively configured.
- This means that they are specified externally to the application source
-
There are two important configuration files for the Validator framework:
- validation-rules.xml
- validation.xml.
- The validation-rules.xml configuration file contains a global set of validation rules.we should need to modify this file only if we plan to modify or extend the default set of rules.
- The second configuration validation.xml file is application-specific.
- It describes which validation rules from the validation-rules.xml file are used by a particular ActionForm.
- This is what is meant by declaratively configured.
Creating own validation rules
- The Validator framework is preconfigured with many of the most common rules .
- If the validation requirements that are not met by the default rules, then you can create your own rules.
-
Several steps to create custom rules are as follows:
- Create a Java class that contains the validation methods.
- Edit the validation-rules.xml file or create your own version. If you do create a new validation resource file, be sure to add it to the list of resource files in the Validator plug-in.
- Use the new validation rules in the validation.xml file for your application.
The validator and JSP custom tags
- Several JSP custom tags included within the Struts tag libraries can be used with the Validator framework.
- One of the tags is used to generate dynamic JavaScript based on the validation rules.
- The Validator framework is also capable of generating JavaScript for our Struts application.
- The Validator custom tag called JavascriptValidator is used to generate client-side validation based on a javascript attribute being present within the validator element.
Internationalizing the validation
- The Validator framework uses the application resource bundles to generate error messages for both client-side and server-side validation for displaying language-specific messages to the user is included within the framework.
-
The validation.xml file supports attributes related to internationalization
- Language
- Country
- Variant
If you do not specify these attributes, then the default Locale is used.
- Using the validator outside of struts
- Although the Validator was originally designed to work with the Struts framework, it can be used to perform generic validation on any JavaBean.
- There are several steps that must be performed before the framework can be used outside of Struts.
- When the Validator framework is used in conjunction with Struts, the org.apache.struts.Validator.ValidatorPlugIn class performs loading and initializing the XML Validator resources.
- Outside of the struts you need to create one java class that will perform initializing the appropriate Validator resources.
Configuring validation-rules.xml |
- The Validator framework allows the validation rules for an application to be declaratively configured.
- This means that they are specified externally to the application source.
-
Two important configuration files for the Validator framework
- validation-rules.xml
- validation.xml
- validation-rules.xml configuration file contains a global set of validation rules.
- This file is application-neutral and can be used by any Struts application.
- You should need to modify this file only if you plan to modify or extend the default set of rules.
The following validator-rules.dtd describes the syntax of the validation-rules.xml file.
<!ELEMENT form-validation (global+)>
<!ELEMENT global (validator+)>
The root element is the form-validation element, which requires one or more global elements
The validator element supports seven attributes
<!ATTLIST validator
name CDATA #REQUIRED
classname CDATA #REQUIRED
method CDATA #REQUIRED
methodParams CDATA #REQUIRED
msg CDATA #REQUIRED
depends CDATA #IMPLIED
jsFunctionName CDATA #IMPLIED>
Note :
If you do need to extend the default rules, you might be better off putting your custom rules in a different XML file, so as to keep them separate from the default ones
name:
- The name attribute assigns a logical name.
- It is used to reference the rule from other rules within this file and from the application-specific validation file e to the validation rule.
- Name must be unique.
classname and method:
Define the class and method that contain the logic for the validation rule.
methodParams:
It is a comma-delimited list of parameters for the method defined in the method attribute.
Msg:
- It is a key from the resource bundle.
- The Validator framework uses this value to look up a message from the Struts resource bundle when a validation error occurs
By default, the Validator framework uses the following values:
errors.required ={0} is required
errors.minlength={0} cannot be less than {1} characters.
errors.maxlength={0} cannot 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 not a valid credit card number.
errors.email={0} is an invalid email address
depends: It is used to specify other validation rules that should be called before the rule specifying it.
Illustration of depends attribute in minlength validation rule:
<validator name="minLength" classname="org.apache.struts.util.StrutsValidator" 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="required" msg="errors.minlength">
</validator>
- If a rule that is specified in the depends attribute fails validation, then the next rule will not be called.
- For example, in the minLength validation rule shown previously, the validateMinLength() method will not be invoked if the required validation rule fails.
- This should stand to reason, because there is no sense in checking the length of a value if no value is present.
jsFunctionName: This optional attribute allows to specify the name of the JavaScript function. org.apache.commons.Validator.
Validation rules in GenericValidator class: The Validator framework is fairly generic. It contains very basic, atomic rules that can be used by any application. The org.apache.commons.Validator.GenericValidator class implements the generic rules as a set of public static methods.
The Struts developers added a utility class to the Struts framework called org.apache.struts.util.StrutsValidator, which defines a set of higher-level methods that are coupled to the Struts framework but make it easier to use the Validator with Struts
Rules | Methods | Description |
---|---|---|
isByte | validateByte | Checks if the value can safely be converted to a byte primitive |
isCreditCard | validateCreditCard | Checks if the field is a valid credit card number |
isDate | validateDate | Checks if the field is a valid date. |
isDouble | validateDouble | Checks if the value can safely be converted to a double primitive. |
isEmail | validateEmail | Checks if the field is a valid email address. |
isFloat | validateFloat | Checks if the value can safely be converted to a float primitive. |
isInRange | validateRange | Checks if the value is within a minimum and maximum range. |
isInt | validateInteger | Checks if the value can safely be converted to an int primitive. |
isLong | validateLong | Checks if the value can safely be converted to a long primitive. |
isShort | validateShort | Checks if the value can safely be converted to a short primitive. |
maxLength | validateMaxLength | Checks if the value’s length is less than or equal to the maximum. |
minLength | validateMinLength | Checks if the value’s length is greater than or equal to the minimum. |
Configuring validation.xml |
- The second configuration file that is required by the Validator framework is the validation.xml file.
- This file is application-specific, as it describes which validation rules from the validation-rules.xml file are used by a particular ActionForm.
- This is what is meant by declaratively configured.
- The validation logic is associated with one or more ActionForm classes through this external file.
Using an ActionForm with the validator |
- An ActionForm represents an HTML form that the user interacts with over one or more pages.
- Maintaining a separate concrete ActionForm class for each form in your application is time-consuming.
- It is particularly frustrating when all the ActionForm does gathering and validating simple properties that are passed along to a business Java Bean.
- So you need to use subclass of ActionForm, which specifically used for validation framework.
-
Two versions of validatorForm
- DynaValidatorForm(DynaValidatorActionForm) , ValidatorForm(ValidatorActionForm)
- The subclass of the ValidatorForm is called ValidatorActionForm , and the subclass of the DynaValidatorForm is called DynaValidatorActionForm .
- The purpose of the two different versions is to allow you to associate the validation with the form-bean definition or the action definition.
Note: For dynamic ActionForms we should use DynaValidatorForm and for standard actionForms we can use ValidatorForm
- The ValidatorActionForm and DynaValidatorActionForm classes pass the path attribute from the action element into the Validator, and the Validator uses the action’s name to look up the validation rules.
- If you use the ValidatorForm or DynaValidatorForm, the name of the ActionForm is used to look up the set of validation rules to use. The only reason for using one or the other is to have more fine-grained control over which validation rules are executed.
Set up the form in struts-config.xml
<struts-config>
<form-beans>
<form-bean name="registerForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property
name="username" type="java.lang.String" />
<form-property
name="password" type="java.lang.String"/>
</form-bean>
</form-beans>
The type represents the exact ActionForm subclass.
Validation.xml file for ActionForm
You need to specify validation rule for each property in validation.xml file.
<form-validation>
<global/>
<formset>
<form name="registerForm">
<field property="username" depends="required,mask">
<arg0 key="errors.username"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value> </var>
</field>
</form>
</formset>
</form-validation>
- For example if the username is required and it should be in specific format means we can give more rules like required,mask in depends attribute.
- These are two separate rules, that both should be true , otherwise the validation will fail.
When you submit the form with no information in the fields, the validation rules kick in and the validation error messages will be displayed in the page.
Plug the validator with Struts |
- Plugging in the validator in struts-config.xml using validator against JSP with struts tags
- You can use plugin mechanism to hook the Validator framework into a Struts application.
Set up the validator as plug-in
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validator.xml"/>
</plug-in>
- The Struts framework will call the init() method in the ValidatorPlugIn class when the application starts up.
- During this method, the Validator resources from the XML files are loaded into memory so that they will be available to the application. Before calling the init() method.
- The pathnames property value is passed to the ValidatorPlugIn instance.
- This is how the ValidatorPlugIn finds out which Validator resources to load.
Examples |
Case Study
Validate the text field in “Example.jsp” page which should not allow the user to submit null values and special characters like ‘*’,’&’ and numbers. Use ValidatorForm, validation.xml file for this purpose.validation error message should be displayed from resource properties.
To enable the javascript validation we need to add <html:javascript formName=”beanName”/> anywhere in the page and add return validateBeanForm(this); in to html:form.
Example
<html:html>
<html:form action="register.do" onsubmit="return
validateExampleForm(this);">
<html:messages id="msg">
Name<html:text property="name" ></html:text>
</html:messages>
<html:submit/>
<html:javascript formName="exampleForm"/>
</html:form>
</html:html>
ExampleForm.java:
The FormBean should extend ValidatorForm instead of ActionForm:
public class ExampleForm extends ValidatorForm
{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
validation.xml
- You need to put one or more validation rules for each fields in validation.xml file.
- Look in properties file to see what args needed and supply arg as necessary:
<form-validation>
<global/>
<formset>
<form name=" exampleForm ">
<field depends="required,mask" property="name">
<arg key="login.username" position="0"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9]*$</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
Configure struts-config.xml
- List the name of the formBean, which is to be validated.
- List the properties file(Application-Resources)
- To enable the validation add “validate=true” in action-mappings, add validator plug-in to turn on automatic validator.
<struts-config>
<form-beans>
<form-bean name="registerForm" type="ExampleForm" />
</form-beans>
<action-mappings>
<action path="/register"
name="exampleForm"
scope="request"
input="/example.jsp"
validate="true">
</action>
</action-mappings>
</struts-config>
<message-resources parameter="ApplicationResources"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB- INF/validation.xml"/>
</plug-in>
Application-Resource properties file
Find the name of the error messages that will be generated if the rules fail from validation-rules.xml. Use those default error messages in Application-Resources properties file
# 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} Should contain only Alpabets.
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.
Flow :
- When Example.jsp page get submitted, control will transfer onsubmit javascript method validateFormName (validateExampleForm) and validate the form.
- If validate=true for the corresponding ExampleForm means, then the control will forward to validation.xml and checks field properties and their rules.
- According to the rule and the key value it will get the error message from ApplicationResources.properties file.
- Html:messages tag will use to display error message in Example.jsp page.
Recent Comments