Custom functions can be registered with Valang to include in your constraints. To imple-
ment a custom function you need to extend org.springmodules.validation.functions.
AbstractFunction. Custom function classes should implement the constructor of its parent
class. The doGetResultmethod implements the actual function logic. Functions in Valang can
have optional arguments, although most functions will probably expect a fixed number of
arguments. The defineMinNumberOfArgumentsand definedMaxNumberOfArgumentsmethods
check whether the number of arguments passed to the function is within the accepted range.
See Listing 9-15.
Listing 9-15.Custom Function That Alters the Case of a String Value
package com.apress.expertspringmvc.validation;
import org.springmodules.validation.functions.AbstractFunction;
import org.springmodules.validation.functions.Function;
import org.apache.commons.lang.WordUtils;
public class AlterCaseFunction extends AbstractFunction {
public AlterCaseFunction(Function[] functions, int line, int column) {
super(functions, line, column);
defineMinNumberOfArguments(1);
defineMaxNumberOfArguments(1);
}
protected Object doGetResult(Object target) {
String value = getArguments()[0].getResult(target).toString();
return WordUtils.swapCase(value);
}
}
AlterCaseFunctionswaps the case for the value of its argument. Its constructor is required
by Valang to instantiate the function. To register this function with Valang we have to configure
it in ValangValidatorFactoryBean, as shown in Listing 9-16.
Listing 9-16.Registering the alterCase Function with Valang
<bean id="caseSwappingValidator"
class="org.springmodules.validation.ValangValidatorFactoryBean">
]]>
CHAPTER 9 ■VALIDATION 275