Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: custom validator is not being called

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?

like image 688
r.rodriguez Avatar asked Nov 04 '13 17:11

r.rodriguez


1 Answers

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.

like image 175
Sanchi Girotra Avatar answered Oct 05 '22 23:10

Sanchi Girotra