gpt4 book ai didi

java - Spring boot 中的字段是否有 'must be numerical' 验证符号?

转载 作者:行者123 更新时间:2023-12-05 06:16:40 25 4
gpt4 key购买 nike

我目前正在开始学习 Spring boot,以及如何在类的字段中使用内置验证工具(anotation)。我知道如何验证字符串并将字段设置为 @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 都提供了很好的答案

最佳答案

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

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

关于java - Spring boot 中的字段是否有 'must be numerical' 验证符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61999926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com