I have an Object called officers i would like to preform different types of validation based on the function the user wants to preform, for e.g when a officer record is being re
You don't need to register your validators in the WebDataBinder
. Instead, you can create two (or any number) different Validator
classes for each of your requirements. For example
public class OfficerRegistrationValidation implements Validator {...}
public class OfficerUpdateValidation implements Validator {...}
Create beans for each of these, either with @Component
or a <bean>
declaration. Inject them in your @Controller
class
@Controller
public class OfficerController {
@Inject
private OfficerRegistrationValidation officerRegistrationValidation;
@Inject
private OfficerUpdateValidation officerUpdateValidation;
Then use the specific one you need in each of your methods
@RequestMapping(method = RequestMethod.POST)
public /* or other return type */ String registerOfficer(@Valid @ModelAttribute Officer officer, BindingResult errors /*, more parameters */) {
officerRegistrationValidation.validate(officer, errors);
if (errors.hasErrors()) {
...// do something
}
...// return something
}
Don't register either of these in the WebDataBinder
. @Valid
will perform default validation, for example, for @NotEmpty
or @Pattern
annotations. Your Validator
instances will perform custom validation for the specific use case.