【问题标题】:How to allow a field to be blank in spring boot?如何在春季启动中允许字段为空白?
【发布时间】:2020-09-25 17:09:54
【问题描述】:

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

这是我的代码

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

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

"mobile":""

提示“手机号码应为 10 位”。

【问题讨论】:

  • 尝试添加@Nullable
  • @silentsudo 我尝试使用可为空的,仍然无法正常工作

标签: java spring spring-boot validation spring-mvc


【解决方案1】:

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

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

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

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

这里,

\\s* - \\s 用于空白字符,* 用于出现零次或多次

| - 交替(或)

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

尝试探索Regular expressions in Java

【讨论】:

    【解决方案2】:

    您还可以将@Nullable 与@Size 结合使用

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

    【讨论】:

    • OP 将“”(空字符串)视为有效输入。可能这不能解决这个问题
    猜你喜欢
    • 2016-09-13
    • 2021-06-10
    • 2021-05-06
    • 1970-01-01
    • 2017-06-26
    • 2020-02-23
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    相关资源
    最近更新 更多