apply custom validator in spring MVC controller in more than one class

前端 未结 2 2018
有刺的猬
有刺的猬 2021-02-11 05:51

I have one registration page which uses custom valiadtor

public class CustomValidator implements Validator {

    private Validator validator;

    public Custom         


        
2条回答
  •  爱一瞬间的悲伤
    2021-02-11 06:38

    You could do this

    public boolean supports(Class clazz) {
        return Registration.class.equals(clazz) || Another.class.equals(clazz);
    }
    

    Then your validate should do something like this

        public void validate(Object target, Errors errors) {
        validator.validate(target, errors);
    
        String password = null;
        String confirm = null;
        if (target instanceof Registration) {
            Registration registration = (Registration) target;
            password = registration.getPassword();
            confirm = registration.getConfirm_password();
        } else if (target instanceof Another) {
            Another another = (Another) target;
            password = another.getPassword();
            confirm = another.getConfirm_password();
        }
        if (! confirm.equals(password())) {
            errors.rejectValue("confirm_password", "confirm_password.confirm");
        }
    
    }
    

    I don't think you should use this probably it is better to use to separate classes is better for readability, and reduces complexity. To introduce hierarchy in your validators or Model objects (Vistor pattern) is not the best solution.

提交回复
热议问题