2

I'm using Hibernate Validator annotations with individual parameters of my Spring @Controller, as shown below:

@RequestMapping(value = URIConstants.SOME_URI, method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> tryValidation(
            @Size(min = 1, max = 20) 
            @NotBlank @RequestParam(required = false) String something) {
        return ResponseEntity.status(HttpStatus.OK).body(something);
    }

As per my understanding, @NotBlank and @NotEmpty both use @NotNull, but what if I want to use @NotBlank without @NotNull? Basically, I want the parameter to not be mandatory, but when it is defined it should not be null or empty. However, when I try to do this, the @RequestParam(required = false) doesn't matter and you end up having to define the parameter.

I know I could write a custom validator but is there a way to do so within the existing functionality of Hibernate Validator?

ystark
  • 565
  • 9
  • 18
  • Possible duplicate of [Spring Web MVC - validate individual request params](http://stackoverflow.com/questions/6203740/spring-web-mvc-validate-individual-request-params) – Ali Dehghani May 04 '16 at 08:04
  • Actually, I did see this post but the question is not the same. I already know how to validate individual params and I'm already doing it as shown in the code. I want to know if a built-in mechanism allows `@NotBlank` without making the parameter mandatory. – ystark May 04 '16 at 08:18
  • 1
    Use `@Length` annotation with `min=1` – Roman Proshin May 04 '16 at 08:22
  • That works! Thanks, @Roman Proshin! By the way, what is the difference between `@Size` and `@Length`? – ystark May 04 '16 at 08:31
  • 1
    @ystark Good question! I found next differences: `Length` - from hibernate lib, but `Size` - from javax.validation. `Length` - for strings only, `Size` - for string and collections. It looks like `Size` is more universal. – Roman Proshin May 04 '16 at 08:40
  • @Roman Proshin, you're right about that. Thanks again! – ystark May 04 '16 at 08:48
  • 1
    `@Length` with `min=1` will allow blank fields though. `" "` passes with a length minimum >= 1, however it would not pass `@NotBlank`. – Andrew_CS May 17 '17 at 19:39

0 Answers0