Validate partial Modal using Spring @Valid annotation

后端 未结 2 1347
暖寄归人
暖寄归人 2020-12-21 17:03

I have a User Modal

public class RegisterUser {

    @Size(min = 2, max = 30)
    private String fname;

    @Size(min = 2, max = 30)
    private String lnam         


        
相关标签:
2条回答
  • 2020-12-21 18:01

    I don't know if this is possible with Bean Validation, but you can set up different implementations of Spring's Validation Interface for different request parameters.

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String submitRegisterForm(@Valid RegisterUser registerUser, ...
    

    and

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String submitMyprofileForm(@Valid RegisterUser registerUserProfile, ...
    

    And then you can use @InitBinder to connect different Validators to your request params. You would add these methods to your controller. Just omit the validation you dont want in the second Validator.

    @InitBinder("registerUser")
    protected void initUserBinder(WebDataBinder binder) {
        binder.setValidator(new RegisterUserValidator());
    }
    
    @InitBinder("registerUserProfile")
    protected void initUserBinderProfile(WebDataBinder binder) {
        binder.setValidator(new RegisterUserProfileValidator());
    }
    

    Then you would need to do the annotation stuff manually. You could also use inheritance for your Validators, because they are exactly the same, except the one additional field validation for registration forms.

    public class RegisterUserValidator implements Validator {
        public boolean supports(Class clazz) {
            return RegisterUser.class.equals(clazz);
        }
    
        public void validate(Object obj, Errors e) {
            ValidationUtils.rejectIfEmpty(e, "publicProfile", "empty");
            RegisterUser r = (RegisterUser) obj;
            if (r.getFname().length() < 2) {
                e.rejectValue("fname", "min");
            } else if (r.getFname().length() > 30) {
                e.rejectValue("fname", "max");
            }
            // ...
        }
    }
    
    0 讨论(0)
  • 2020-12-21 18:05

    You can use Validation Groups (for different scenarios) and Spring's @Validated annotation to specify which group you want to use

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