20

I have this field declared in a model class:

@Size(min = 2, max = 200, message = "{validation.name.size}")
private String name;

where validation.name.size is the path to a localized message. The problem is that I do not want to output a message like 'The name is too long or too short.'.

Is there any way to use two different messages and check minimum and maximum string length? @Min and @Max are only working for numeric types, so they can not be used. What is the alternative for strings?

F_Schmidt
  • 902
  • 1
  • 11
  • 32

3 Answers3

33

You can just use the "@Size"-annotation twice:

@Size(min = 2, message = "{validation.name.size.too_short}")
@Size(max = 200, message = "{validation.name.size.too_long}")
private String name;
Fabian
  • 466
  • 5
  • 6
4

Yes there is - you can use the @Size.List() and @Size annotations in conjunction like so:

@Size.List({
     @Size(min = 2, message = "{validation.name.size.too_short}"),
     @Size(max = 10, message = "{validation.name.size.too_long}")
})
Gabe
  • 41
  • 2
0

another option could be to use a regex. something like

^[a-zA-Z0-9]]{2,200}$

it depends if you want to control the characters.

Spilvergo
  • 31
  • 4