Laures
Laures

Reputation: 5479

jsr-303 annotations on a spring mvc controller parameter

Is it possible to use Bean Validation annotations like @Past or @Length on Request Parameters in spring mvc?

I would like to do something like:

@RequestMapping(method = RequestMethod.POST)
public RedirectView initiateSignup(@RequestParam @Valid @Past Date birthdate, BindingResult birthdateResult,
        HttpServletResponse httpServletResponse) throws HttpMediaTypeNotAcceptableException {

Upvotes: 1

Views: 2544

Answers (2)

Laures
Laures

Reputation: 5479

I made it work with the help of a blog post:

http://blog.codeleak.pl/2012/03/how-to-method-level-validation-in.html

an additional annotation and a bean post processor were nessecary, but now it works.

Upvotes: 1

sdouglass
sdouglass

Reputation: 2390

I don't think that's possible. You can apply @Valid but not e.g. @Past. You can instead create a model class with fields that correspond to your request parameters, and put the JSR-303 annotations on the class's fields. You can then use that class as the controller method argument type, with @Valid on it, and Spring should validate it appropriately.

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/validation.html#validation-mvc-jsr303

Upvotes: 0

Related Questions