The message attribute defines the message (or error code) to return when the
·
constraint is violated. Default message can also be provided in the annotation.
The groups attribute specifies the validation group if applicable. It's possible to
·
assign validators to different groups and perform validation on a specific group.
The payload attribute specifies additional payload objects (of the class
·
implementing the javax.validation.Payload interface). It allows you to attach
additional information to the constraint (for example, a payload object can
indicate the severity of a constraint violation).
Listing 14-26 shows the IndividualCustomerValidator class that provides the validation logic.
Listing 14-26. The IndividualCustomerValidator Class
package com.apress.prospring3.ch14.jsr303.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.apress.prospring3.ch14.domain.Customer;
public class IndividualCustomerValidator implements
ConstraintValidator<CheckIndividualCustomer, Customer> {
public void initialize(CheckIndividualCustomer constraintAnnotation) {
}
public boolean isValid(Customer customer,
ConstraintValidatorContext context) {
boolean result = true;
if (customer.getCustomerType() != null &&
(customer.isIndividualCustomer()
&& (customer.getLastName() == null ||
customer.getGender() == null))
){
result = false;
}
return result;
}
}
In Listing 14-26, the IndividualCustomerValidator implements the
ConstraintValidator<CheckIndividualCustomer, Customer> interface, which means that the validator
checks the CheckIndividualCustomer annotation on the Customer classes. The isValid() method is
implemented, and the underlying validation service provider (for example, Hibernate Validator) will
pass the instance under validation to the method. In the method, we verify that if the customer is an
individual, then the lastName and gender properties should not be null. The result is a boolean value that
indicates the validation result.
To enable the validation, apply the @CheckIndividualCustomer annotation to the Customer class, as
shown in Listing 14-27.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home