Tuesday, June 8, 2010

Struts 2: Locale Specific Validation XML

Problem:

Using one form over multiple countries with fields possibly changing business rules and validation requirements per country.
The Struts 2 validation system is a very elegant way to validate form input on the client and server side. We wanted to use the validation components including the struts-tags but the struts validation system is very much a black box without much information about how to tear it apart. Our other requirements were that we had a dynamic form changing based on country. This didn't seem like a unique problem to me for those developing enterprise software this is a common situation. In fact the struts documentation goes into localization of labels (which didn't work for us because we use a database driven local system).

Solution:

1.
There is possibly a better solution but this is what I came up with that will work for our needs.  We decided to use the wild card syntax in our action name to allow us to append the country on the end of the URL.
<action class="com.myBiz.SomeAction" name="Save*">
             <result>success.jsp</result>
</action>

2. 
Once we have that in place then we can use the validation 'alias' to capture the correct XML definition for our rules.  It wasn't completely clear to me what the alias was but after some quick testing it correlates with the name attribute of the action.  So here is the name of my validation definition.
SomeAction-SaveUS-validation.xml
I can also use the main validation for a default where fields that don't have special rules per country can be defined.
SomeAction-validation.xml
Keep in mind however that all defined rules will be executed so if you were to require firstName in the SomeAction-validation.xml and in the SomeAction-SaveUS-validation.xml both required will be executed and you will have double error messages.

3.
The last part of this is telling the form what country it needs to submit too.

<form action="Save${country}" > </form> Something like that.

I don't think this is the most elegant solution and there will probably be gotchas along the way.  However, this solution fits our needs today and I have a deadline to meet.


No comments: