[英]How can I validate the string length using java spring validation?
I have this field declared in a model class:我在 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.其中
validation.name.size
是本地化消息的路径。 The problem is that I do not want to output a message like 'The name is too long or too short.'.问题是我不想向 output 发送“名称太长或太短”之类的消息。
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. @Min
和@Max
只对数字类型起作用,所以不能使用。 What is the alternative for strings?字符串的替代品是什么?
You can just use the "@Size"-annotation twice:您可以只使用“@Size”注释两次:
@Size(min = 2, message = "{validation.name.size.too_short}")
@Size(max = 200, message = "{validation.name.size.too_long}")
private String name;
another option could be to use a regex.另一种选择是使用正则表达式。 something like
就像是
^[a-zA-Z0-9]]{2,200}$ ^[a-zA-Z0-9]]{2,200}$
it depends if you want to control the characters.这取决于你是否想控制角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.