首页 > 解决方案 > Spring boot 中的字段是否有“必须为数字”的验证符号?

问题描述

我目前正在开始学习 Spring boot,以及如何在类的字段中使用内置的验证工具(注解)。我知道如何验证 String 并将字段设置为@NotNull,但无法找到任何方法对数值执行相同操作。我考虑过将@Pattern用于正则表达式,但希望有更清晰(更容易)使用的东西。

我不想设置@Min@Max。它应该能够使用所有可能的 int 数值。

当前代码,我想在 zipCode 处设置符号(最后一个字段)

@Entity
public class Customer {
    @Id
    private int id;
    @NotNull
    @Size(min=2,max=15)
    private String firstName;
    @NotNull
    @Size(min=2,max=15)
    private String lastName;
    @NotNull
    @Size(min=5,max=45)
    private String address;
    @NotNull
    @Size(min=1,max=15)
    private String driversLicense;
    @NotNull
    @Size(min=1, max=3)
    private String licensesType;
    @NotNull
    @Size(min=1,max=30)
    private String phone;
    @NotNull
    @Size(min=1,max=15)
    private String nationality;
    @NotNull
    @Size(min=1,max=30)
    private String city;
    @NotNull
    private int zipCode;

使用@NotNull表示法,我得到的错误消息是

Failed to convert property value of type java.lang.String to required type int for property zipCode;
nested exception is java.lang.NumberFormatException: For input string:"xx"

并希望它成为客户错误消息,但是当我这样做时

@NotNull(message="Custom error message") 
private int zipCode

我仍然收到上述错误消息。

任何解决这两个问题的想法,将不胜感激

编辑:没有意识到这个问题只能有一个“批准”的答案。由于这是两个问题,@Pankaj 和 @JArgente 都提供了很好的答案

标签: javaspringspring-bootvalidationinput

解决方案


您遇到的问题是此错误是在验证之前产生的,在解散阶段,我的意思是首先spring尝试将输入json转换为您在类中指定的类型,然后验证输入以确保约束已满,(例如,字符串在大小指定的边界之间。等)。

因此,自定义所需消息的方法是创建自定义反序列化器或将该属性标记为 String 并检查自己是否存储了有效数字,如果没有,则使用自定义消息。


推荐阅读