01
Aug
09

Spring MVC Validation using Commons Validator


This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.

This article will show you how to integrate Spring MVC with the commons validator framework.

Requirements:
If you have not done so already please read the following link to get started.

The commons validator is a core set of classes responsible for validating data. The down side of commons validation is that you can not use it directly out of the box. Typically there is some wrapper code that is necessary. Struts provided this wrapper code in the org.apache.struts.validator package.

Instead of packaging this code into Spring MVC the developers of the framework decided to included it as a module ontop of the Spring framework.

The spring validation module provides support modules that allows the commons validator to be integrated with the spring framework.

insert the following dependency in pom.xml and regenerate your eclipse project.

 		 <dependency>
			<groupId>org.springmodules</groupId>
			<artifactId>spring-modules-validation</artifactId>
			<version>0.8</version>
 		</dependency>
 		<dependency>
			<groupId>commons-validator</groupId>
			<artifactId>commons-validator</artifactId>
			<version>1.1.4</version>
 		</dependency>

This will get the spring-modules-validation onto your machine as well as commons-validator. The main class in the spring validator module is the FieldChecks this class contains almost all the necessary items that you may need to implement in your commons-validator code.

At the time of this writing the following were the methods and the necessary code to include into the validator-rules.xml file.

All the methods have the same signature except

  • requiredIf
  • requiredWhen

You need to include the following in whatever resource bundle your web application uses…

Read my article on Web Application Resource Bundles

   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.

This is what validator-rules will look like if you are using the Spring MVC framework with commons loggingâ?¦

/WEB-INF/validator-rules.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>
	<global>
		<validator name="required"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateRequired"
			methodParams="java.lang.Object,
                        org.apache.commons.validator.ValidatorAction,
                        org.apache.commons.validator.Field,
                        org.springframework.validation.Errors"
			msg="errors.required">
		</validator>
		<validator name="requiredif"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateRequiredIf"
			methodParams="java.lang.Object,
                               org.springframework.validation.ErrorsAction,
                               org.apache.commons.validator.Field,
                               org.springframework.validation.Errors"
			msg="errors.required" />

		<validator name="validwhen" msg="errors.required"
			classname="org.apache.struts.validator.validwhen.ValidWhen" method="validateValidWhen"
			methodParams="java.lang.Object,
                       org.springframework.validation.ErrorsAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors" />

		<validator name="minlength"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateMinLength"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.minlength"
			jsFunction="org.apache.commons.validator.javascript.validateMinLength" />

		<validator name="maxlength"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateMaxLength"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.maxlength"
			jsFunction="org.apache.commons.validator.javascript.validateMaxLength" />

		<validator name="mask"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateMask"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.invalid" />

		<validator name="byte"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateByte"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.byte" jsFunctionName="ByteValidations" />

		<validator name="short"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateShort"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.short" jsFunctionName="ShortValidations" />

		<validator name="integer"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateInteger"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.integer" jsFunctionName="IntegerValidations" />

		<validator name="long"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateLong"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.long" />

		<validator name="float"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateFloat"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.float" jsFunctionName="FloatValidations" />

		<validator name="double"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateDouble"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.double" />

		<validator name="date"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateDate"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.date" jsFunctionName="DateValidations" />

		<validator name="intRange"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateIntRange"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="integer" msg="errors.range" />

		<validator name="floatRange"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateFloatRange"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="float" msg="errors.range" />

		<validator name="doubleRange"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateDoubleRange"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="double" msg="errors.range" />

		<validator name="creditCard"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateCreditCard"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.creditcard" />

		<validator name="email"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateEmail"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.email" />

		<validator name="url"
			classname="org.springmodules.validation.commons.FieldChecks" method="validateUrl"
			methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.springframework.validation.Errors"
			depends="" msg="errors.url" />
	</global>
</form-validation>

In the validation.xml all the forms that will be used in the application will be defined. The layout of this file is very similar to the validation-rules.xml however we don’t have have anything in the global section.

validation.xml

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

	<formset>
		<form name="address">
			<field property="name" depends="required">
				<arg0 key="info.name" />
			</field>
			<field property="city" depends="required">
				<arg0 key="info.city" />
			</field>
			<field property="street" depends="required">
				<arg0 key="info.street" />
			</field>
			<field property="state" depends="required">
				<arg0 key="info.state" />
			</field>
			<field property="zip" depends="integer">
				<arg0 key="info.zip" />
			</field>
		</form>
	</formset>
</form-validation>

In the item above the first argument for each property is the key to the resource bundle entry that will display the error.

Insert the following into the resource bundle property file

nameEmpty=Name is empty
info.name=Name
info.city=City
info.street=Street Address
info.state=State

I needed to insert the following into my spring-servlet.xml and change the validator for my SimpleFormController to the commons validator.

<bean id="validatorFactory"
      class="org.springmodules.validation.commons.DefaultValidatorFactory">
<property name="validationConfigLocations">
	<list>
      <value>/WEB-INF/validation.xml</value>
      <value>/WEB-INF/validator-rules.xml</value>
    </list>
  </property>
</bean>

<bean id="beanValidator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>

That’s All!!! You now have a fully configured Spring MVC system with Commons Validator

Special Notes:
Currently the client side javascript code generation and validation is not working. This issue is discussed at the following url:
http://jira.springframework.org/browse/MOD-402
I would encourage you guys to register with that site and vote for the issue to get fixed.

This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.
Advertisements

2 Responses to “Spring MVC Validation using Commons Validator”


  1. 1 Henrik Martinussen
    October 7, 2009 at 2:29 pm

    Thank you so much, Neeraj
    This Blog entry seems to contain exactly the information I need :-)
    I’m playing around with the RoadRants example from “Spring in Action”. Currently I am working on getting some experience with Spring MVC.
    I need the experience to finish a small project, involving maven2 eclipse Springframework Hibernate HSQLDB etc.
    Thanks again,
    Nice Regards
    Henrik Martinussen


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 74 other followers

August 2009
S M T W T F S
« Jul   Sep »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Blog Stats

  • 801,397 hits

%d bloggers like this: