简体   繁体   中英

Spring Validation: get single (relevent) validation message for multiple constraints

I have multiple constraints applied on a single field name like:

@NotNull
@Min(value=3, message="Name should be atleast 3 chars long")
@Max(value=40, message="Name can not be longer than 40 chars")
@Pattern(regexp="[a-zA-Z]+", message="Name can only contain letters")
String name;

For a value of "af3" of that field, I am getting all the above 4 messages. I want to display only the relevent ones which apply. ie, in this case, message should be "Name can only contain letters"

@Max and @Min are for numbers only, that's why you get those messages. According to the docs (similar text for min ):

The annotated element must be a number whose value must be lower or equal to the specified maximum.

Supported types are:

BigDecimal BigInteger byte, short, int, long, and their respective wrappers

@Size (and max/min) can be used for validating String length, similarly @Length (from hibernate validators) and max/min parameters is used to validate length of a String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM