如何让Spring Boot中的字段为空?

Fak*_*ipo 3 java validation spring spring-mvc spring-boot

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

这是我的代码

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

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

"mobile":""
Run Code Online (Sandbox Code Playgroud)

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

Ekl*_*vya 5

要接受包含空格或恰好 10 个字符的空白值字符串,请尝试以下操作

@Pattern(regexp = "\\s*|.{10}")
private String mobile;
Run Code Online (Sandbox Code Playgroud)

仅接受空字符串或恰好 10 个字符

@Pattern(regexp = "|.{10}")
private String mobile;
Run Code Online (Sandbox Code Playgroud)

这里,

\\s*-\\s对于空白字符并且*for 出现零次或多次

|- 交替 (OR)

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

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