Recently I’ve worked on how to improve built-in validators in the Apache Struts 2. The basic idea was to allow specify configuration params of the validators as OGNL expressions. Till now you could only statically define these params which was a bit suboptimal. See the example below:

<validator type="stringlength">
    <param name="fieldName">myPurchaseCode</param>
    <param name="minLength">1</param>
    <param name="maxLength">10</param>
    <message>Your purchase code needs to be between 1 to 10 characters long</message>
</validator>

As you see you can only define minLength / maxLength as a static value which sometimes isn’t enough. Quite often you would like depend on a user input or assigned privileges to the user and so on. Having option to dynamically adjust the minLength and maxLength is a nice future, though 🙂

Someone else noticed the same and registered an issue WW-2923, I’ve extended it a bit and added all the sub-tasks to handle each available validator step-by-step. I had to change not only the code, but also documentation. Maybe it’s obvious but very frequently we (developers) forget about that – and then myth like JavaDocs are useless come to light 😉

Anyway, my first thought was to implement the enhancement based on the current param names and just add logic to parse param’s value as an OGNL expression, see below:

<validator type="stringlength">
    <param name="fieldName">myPurchaseCode</param>
    <param name="minLength">${minLenghtValue}</param>
    <param name="maxLength">${maxLengthValue}</param>
    <message>Your purchase code needs to be between ${minLength} to ${maxLength} characters long</message>
</validator>

The problem with this approach is that it breaks backward compatibility, also if you want to use just static values as above, there is an additional overhead – OGNL parser will try to evaluate the expression and fallback to the original value – which is costly.

Then I simple added another set of params to allow specify only these params as an OGNL expression, so you can decide when to use the static values or when to use expressions or when to mix all of them. Thus also simplify migration of existing applications as a developer can migrate each validation when he needs that.

<field-validator type="stringlength">
    <param name="minLengthExpression">${minLengthValue}</param>
    <param name="maxLengthExpression">${maxLengthValue}</param>
    <param name="trimExpression">${trimValue}</param>
    <message>Your purchase code needs to be between ${minLength} to ${maxLength} characters long</message>
</field-validator>

If you want to know more please read the docs. You can try to play with the latest build if you want to use this future. I’m going to work on another improvement in Apache Struts 2 🙂