Search code examples
javaspringstringvalidationspring-validator

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?


Solution

  • 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;