If you use JSR 303 Bean validation, you can use groups
to do this.
Suppose you have this user input containing two sections. Two boolean values ββindicating whether partitions are enabled or disabled. (Of course, you can use more useful annotations than @NotNull
)
public class UserInput { boolean sectionAEnabled; boolean sectionBEnabled; @NotNull(groups=SectionA.class) String someSectionAInput; @NotNull(groups=SectionA.class) String someOtherSectionAInput; @NotNull(groups=SectionB.class) String someSectionBInput; Getter and Setter }
You need two interfaces for groups. They work only as a marker.
public interface SectionA{} public interface SectionB{}
Since Spring 3.1, you can use the Spring @Validated
annotation (instead of @Validate
) in your controller method to trigger validation:
@RequestMapping... public void controllerMethod( @Validated({SectionGroupA.class}) UserInput userInput, BindingResult binding, ...){...}
Prior to Spring 3.1, it was not possible to specify the verification group that should be used for verification (since @Validated
does not exist and @Validate
does not have a group attribute), so you need to start the verification using manually written code. This is an example of how to initiate a check based on the witch partition included in Spring 3.0.
@RequestMapping... public void controllerMethod(UserInput userInput,...){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); List<Class<?>> groups = new ArrayList<Class<?>>(); groups.add(javax.validation.groups.Default.class); //Always validate default if (userInput.isSectionAEnabled) { groups.add(SectionA.class); } if (userInput.isSectionBEnabled) { groups.add(SectionB.class); } Set<ConstraintViolation<UserInput>> validationResult = validator.validate(userInput, groups.toArray(new Class[0])); if(validationResult.isEmpty()) { ... } else { ... } }
(BTW: for Spring 3.0, you can also let Spring introduce a validator:
@Inject javax.validation.Validator validator <mvc:annotation-driven validator="validator"/> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource" ref="messageSource" /> </bean>
)