Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate the string length using java spring validation?

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?

like image 873
F_Schmidt Avatar asked Aug 30 '25 14:08

F_Schmidt


2 Answers

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;
like image 72
Fabian Avatar answered Sep 02 '25 05:09

Fabian


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}")
})
like image 20
Gabe Avatar answered Sep 02 '25 05:09

Gabe