39

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?

3
  • Why not "the name must be between 2 and 200 characters"? Commented Jul 2, 2021 at 23:18
  • I think this isn't really user friendly. I'd prefer two separat validations. Commented Jul 2, 2021 at 23:21
  • Maybe not the most realistic example but as a User I may enter a String size 1. I get, "string to short", now I write "thisisaverylongstring......". And now I get "string to long". Isn't this more annoying than the message provided by @chrylis-cautiouslyoptimistic- ? Commented Dec 1, 2023 at 7:07

3 Answers 3

70

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;
Sign up to request clarification or add additional context in comments.

Comments

6

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}")
})

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.