java - 如何在春季启动中允许字段为空白?
问题描述
我正在尝试对电话号码进行验证,我们可以允许它为空和空。但只有在输入时,它才必须是 10 个字符的大小。
这是我的代码
@Size(max=10,min=10, message = "mobile no. should be of 10 digits")
private String mobile;
当我根本不传递任何值时,会接受 null,但是当我传递这样的空字符串时。
"mobile":""
它给了我“手机号码应该是10位数字”的错误。
解决方案
要接受包含空格或精确 10 个字符的空值字符串,请尝试此操作
@Pattern(regexp = "\\s*|.{10}")
private String mobile;
只接受空字符串或精确的 10 个字符
@Pattern(regexp = "|.{10}")
private String mobile;
这里,
\\s*
-\\s
对于空格字符和*
for 出现零次或多次
|
- 交替(或)
.{10}
- .
for 匹配任何字符并且{10}
for 出现 10 次
尝试探索Java中的正则表达式
推荐阅读
- wordpress - 仅显示自定义分类的主要类别 (yoast)
- javascript - PDF Javascript中的字符串到二维数组
- c# - 如何使对象跟随航路点到中心点?
- python - 获取 GBDT 模型树信息的信息
- xamarin.forms - xamarin 表单:将 jarray 空值发布到 Web api
- r - “匹配错误(x,表,nomatch = 0L):'匹配'需要向量参数”
- java - ByteBuddy 附加到本地正在运行的进程
- java - 比较 Java 中的状态
- php - Codeigniter 中的取消链接功能不起作用
- javascript - 当我重新加载页面时,受污染的画布可能不会在 chrome 上导出错误