Listing 14-27. Applying Custom Validation to the Customer Class
package com.apress.prospring3.ch14.domain;
// Import statements omitted
@CheckIndividualCustomer
public class Customer {
// Other code omitted
}
To test the custom validation, add the code snippet in Listing 14-28 to the main() method of the
testing class (Jsr303Sample) in Listing 14-24.
Listing 14-28. Applying Custom Validation to the Customer Class
// Test custom constraints
customer.setFirstName("Clarence");
customer.setLastName("Ho");
customer.setCustomerType(CustomerType.INDIVIDUAL);
customer.setGender(null);
validateCustomer(customer, myBeanValidationService);
Running the program produces the following output (the other output was omitted):
No. of violations: 1
Validation error for property:  with value: com.apress.prospring3.ch14.domain.Customer@d3f136e
with error message: Individual customer should have gender and last name defined
In the output, you can see that the value under check (which is the Customer object) violates the
validation rule for individual customers, because the gender attribute is null. Note also that in the
output, the property path is empty, because it's a class-level validation error.
Using AssertTrue for Custom Validation
Besides implementing a custom validator, another way to apply custom validation in the Bean
Validation API is using the @AssertTrue annotation. Let's see how it works.
For the Customer class, remove the @CheckIndividualCustomer annotation and add the code snippet
in Listing 14-29 to the Customer class.
Listing 14-29. Applying @AssertTrue to the Customer Class
package com.apress.prospring3.ch14.domain;
// Import statements omitted
public class Customer {
// Codes omitted
@AssertTrue(message="Individual customer should have gender and last name defined")
private boolean isValidIndividualCustomer() {
boolean result = true;
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home