我对单个字段名称应用了多个约束,例如:
@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;
对于该字段的值“af3”,我收到了上述所有 4 条消息。我只想显示适用的相关内容。即,在这种情况下,消息应该是“名称只能包含字母”
最佳答案
@Max
和 @Min
仅适用于数字,这就是您收到这些消息的原因。根据docs (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
(和最大/最小)可用于验证字符串长度,类似地
@Length
(来自 hibernate validator )和 max/min 参数用于验证字符串的长度。
关于java - Spring 验证: get single (relevent) validation message for multiple constraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478168/