首页 > 解决方案 > 如何在春季启动中允许字段为空白?

问题描述

我正在尝试对电话号码进行验证,我们可以允许它为空和空。但只有在输入时,它才必须是 10 个字符的大小。

这是我的代码

    @Size(max=10,min=10, message = "mobile no. should be of 10 digits")
    private String mobile;

当我根本不传递任何值时,会接受 null,但是当我传递这样的空字符串时。

"mobile":""

它给了我“手机号码应该是10位数字”的错误。

标签: javaspringspring-bootvalidationspring-mvc

解决方案


要接受包含空格或精确 10 个字符的空值字符串,请尝试此操作

@Pattern(regexp = "\\s*|.{10}")
private String mobile;

只接受空字符串或精确的 10 个字符

@Pattern(regexp = "|.{10}")
private String mobile;

这里,

\\s*-\\s对于空格字符和*for 出现零次或多次

|- 交替(或)

.{10}- .for 匹配任何字符并且{10}for 出现 10 次

尝试探索Java中的正则表达式


推荐阅读