验证 Java LocalDate 是否匹配 yyyy-MM-dd 格式和可读消息

我在 DoB 的 POJO 类中有以下属性。


@NotNull(message = "dateOfBirth is required")

@JsonDeserialize(using = LocalDateDeserializer.class)

LocalDate dateOfBirth;

我该如何验证


用户正在发送有效的日期格式(仅接受 YYYY-MM-DD)

如果用户输入的日期不正确,我想发送自定义消息或更具可读性的消息。目前,如果用户输入无效日期,则应用程序会发送以下长错误 -

JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String \"1984-33-12\": Failed to deserialize java.time.LocalDate:

(java.time.format.DateTimeParseException) Text '1984-33-12' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 33; 

...


繁花不似锦
浏览 313回答 3
3回答

MMTTMM

您可以使用此注释:@JsonFormat(pattern = "YYYY-MM-DD")您可以在此处进一步阅读有关验证日期格式时自定义错误消息的信息: 自定义错误消息

梵蒂冈之花

您应该创建自定义反序列化器,覆盖反序列化方法以抛出自定义错误并在@JsonDeserialize 中使用它public class CustomDateDeserializer&nbsp; &nbsp; &nbsp; &nbsp; extends StdDeserializer<LocalDate> {&nbsp; &nbsp; private static DateTimeFormatter formatter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = DateTimeFormatter.ofPattern("YYYY-MM-DD");&nbsp; &nbsp; public CustomDateDeserializer() {&nbsp; &nbsp; &nbsp; &nbsp; this(null);&nbsp; &nbsp; }&nbsp; &nbsp; public CustomDateDeserializer(Class<?> vc) {&nbsp; &nbsp; &nbsp; &nbsp; super(vc);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public LocalDate deserialize(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JsonParser jsonparser, DeserializationContext context)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; String date = jsonparser.getText();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return LocalDate.parse(date, formatter);&nbsp; &nbsp; &nbsp; &nbsp; } catch (DateTimeParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new RuntimeException("Your custom exception");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}用它:@JsonDeserialize(using = CustomDateDeserializer.class)LocalDate dateOfBirth;

POPMUISE

像这样的东西。@Column(name = "date_of_birth")@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE)@JsonFormat(pattern = "YYYY-MM-dd")private LocalDateTime dateOfBirth;DateTimeFormatter Java 文档https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java