SpringMvc How to use different validators for an Object based on the function the user is preforming

前端 未结 1 1565
悲哀的现实
悲哀的现实 2021-02-06 15:00

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

相关标签:
1条回答
  • 2021-02-06 15:50

    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.

    0 讨论(0)
提交回复
热议问题