Reputation: 1132
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?
Upvotes: 37
Views: 79940
Reputation: 76
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.
Upvotes: 0
Reputation: 61
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}")
})
Upvotes: 6
Reputation: 806
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;
Upvotes: 66