Search code examples
javaspringspring-bootbean-validationhibernate-validator

javax bean validation not working on method parameters


javax validation not working on method parameters.. This is a test code and none of javax validation works on method parameter...

@RequestMapping(value = "/{id}", method = RequestMethod.PUT, params = "action=testAction")
public Test update(
        @Size(min = 1) @RequestBody List<String> ids,
        @Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}

But i have class level validations which works perfectly...

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public RoleType create (@RequestBody @Validated(FieldType.class) User user) {
    ...
}

And

@Size(min = 2, max = 10, groups = { FieldType.class }, message = "Invalid user code")
 public String getId() {
    return _id  ;
}

-- Solution --

all steps followed as per the accepted answer. And another addition is annoation on class level

@Validated
class UserController
{
   @RequestMapping(value = "/{id}", method = RequestMethod.PUT, params ="action=testAction")
   public Test update(@Size(min = 1) @RequestBody List<String> ids,@Min(3) @PathVariable String name) {
    return doSomething(ids, name);
}
}

Solution

  • you need to register MethodValidationPostProcessor bean to kick method level validation annotation

    delegates to a JSR-303 provider for performing method-level validation on annotated methods.

      @Bean
         public MethodValidationPostProcessor methodValidationPostProcessor() {
              return new MethodValidationPostProcessor();
         }
    

    then,

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Test update(
            @Size(min = 1) @RequestBody List<String> ids,
            @Min(3) @PathVariable("id") String name) {
        return doSomething(ids, name);
    }
    

    if you want to handle validation exception

    @ExceptionHandler(value = { ConstraintViolationException.class })
     @ResponseStatus(value = HttpStatus.BAD_REQUEST)
     public String handleResourceNotFoundException(ConstraintViolationException e) {
          Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
          StringBuilder strBuilder = new StringBuilder();
          for (ConstraintViolation<?> violation : violations ) {
               strBuilder.append(violation.getMessage() + "\n");
          }
          return strBuilder.toString();
     }