I was looking at other questions about Spring custom validators but unfortunately I could not solve my problem with the proposed answers.
My problem is the following: I have an entity (Account) and I created a custom validator (AccountValidator) which I use in a controller (RegisterController), but it is never invoked, using the default Validator.
Am I forgetting something? I attach part of the code to help understand better my problem.
Validator:
public class AccountValidator implements Validator{
    @Override
    public boolean supports(Class<?> clazz) {
        return (Account.class).isAssignableFrom(clazz);
    }
    @Override
    public void validate(Object target, Errors errors) {
    //Validation code
    }
}
Controller:
@Controller
@RequestMapping(value = "/register")
public class RegisterController {
    @Autowired
    private AccountValidator accountValidator;
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields("id");
        binder.setValidator(accountValidator);
    }
    @RequestMapping(method = RequestMethod.GET)
    @ModelAttribute
    public Account register(Locale currentLocale){
        Account account = new Account();
        return account;
    }
    @RequestMapping(method = RequestMethod.POST)
    public String handleRegister(@Valid @ModelAttribute Account account, BindingResult result){
        if(result.hasErrors()){
            return "/register";
        }
        return "home";
    }
}
I checked my debug messages in the log, and the initBinder method is being called, but the validation method is never being executed.
Can anyone help me?
I was facing the same issue and i fixed it by declaring the class AccountValidator in context xml file and using @validated in place of @valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With