Listing 9-5.Valang Validator and Configuration for Address Objects
<bean id="easyAddressValidator" ➥
class="org.springmodules.validation.ValangValidatorFactoryBean">
<property name="syntax">
<value><![CDATA[
{ location :? is not blank : 'Location must be specified' : ➥
'addressLocationEmpty' }
]]></value>
</property>
</bean>
Rewriting the address Validatorwith Valang is straightforward. Remember that the prop-
erty in a constraint is rejected if the constraint evaluates to false. The constraint thus specifies
which conditions must be matched for the object to be valid. Refer to Listing 9-6.
Listing 9-6.Valang Validating Multiple Properties in One Validator
{ city :? is not blank : '' : 'cityEmpty' }
{ location :? is not blank : '' : 'locationEmpty' }
{ postalCode :? is not blank : '' : 'postalCodeEmpty' }
{ country :? is not blank : '' : 'countryEmpty' }
When we want to extend the constraints for the address Validatorin Valang it’s important
to take into account whether all constraints you specify are validated, as well as whether one
or more constraints fail.
If we want to add a constraint that tests the length of the city name, we have to take into
account that the previous constraint that tests whether the city name is blank may have failed.
In other words we need to take into account that the city name may be null.
To achieve this, we let the second constraint succeed if city is blank. See Listing 9-7.
Listing 9-7.Example of Cascading Constraints in Valang
{ city :? is not blank : '' : 'cityEmpty' }
{ city :? is blank or length(?) <= 30 : '' : 'cityTooLong' }
The first constraint will reject the city property value if it’s blank. The second constraint
will only reject the city property value if it’s not blank and it’s more than 30 characters long.
We don’t want to reject the city property in the second constraint if it’s blank because the
first constraint does this already. We do test whether the city property value is blank because
we don’t want a NullPointerExceptionto be thrown when we test the length of the property
value.
The example constraints shown in Listing 9-7 reveal that Valang supports complex logical
tests. AND and OR logical operators are supported next to parentheses to define the order of
prevailing.
Let’s write a rather unrealistic constraint (Listing 9-8) to demonstrate complex tests.
268 CHAPTER 9 ■VALIDATION