简体   繁体   English

如何使用 java spring 验证来验证字符串长度?

[英]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.

相关问题 Java:如何使用RegEx解析和验证字符串? - Java: How can I parse and validate a string using RegEx? 如何在Java中验证字符串是否是字符串而不是整数? - How can I validate if a string is a string and not an integer in java? 如何使用java验证字符串 - How to validate string using java 如何在 Spring boot 中使用 Spring Validation 验证嵌套对象? - How to validate the Nested Objects using Spring Validation in Spring boot? 如何在Java中仅使用charAt(),length()和/或toCharArray()从字符串中提取数字 - How can I extract the numbers from a string only using charAt(), length() and/or toCharArray() in Java 如何在 Java 中初始化长度为 0 的字符串数组? - How can I initialize a String array with length 0 in Java? 使用Java 8流API的字符串长度和字符验证 - String length and character validation using Java 8 stream API 如何在Java中使用日期API验证年份 - How can I validate year using date API in java 我们如何在不使用任何内置函数的情况下找到Java中String的长度? (甚至不包括charAt()或toCharArray()或length()) - How can we find the length of a String in Java without using any inbuilt functions? (not even charAt() or toCharArray() or length()) 如何获取使用Java在文本框中输入的文本的长度? - How can I get the length of text entered in a textbox using java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM