Java LocalDate的验证

时间:2019-08-05 23:06:08

标签: java java-8

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

    @NotNull(message = "dateOfBirth is required")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate dateOfBirth;

我该如何验证

  1. 用户正在发送有效的日期格式(仅接受YYYY-MM-DD)
  2. 如果用户输入的日期不正确,我想发送自定义消息或更具可读性的消息。当前,如果用户输入了无效日期,则应用程序将发送以下长时间错误-

    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; 
    .......
    

3 个答案:

答案 0 :(得分:0)

您可以使用以下注释:

@JsonFormat(pattern = "YYYY-MM-DD")

在此处验证日期格式时,您可以阅读有关自定义错误消息的更多信息: custom error message

答案 1 :(得分:0)

您应该创建自定义反序列化器,覆盖反序列化方法以引发自定义错误,并在@JsonDeserialize中使用它

public class CustomDateDeserializer
        extends StdDeserializer<LocalDate> {

    private static DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("YYYY-MM-DD");

    public CustomDateDeserializer() {
        this(null);
    }

    public CustomDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public LocalDate deserialize(
            JsonParser jsonparser, DeserializationContext context)
            throws IOException {

        String date = jsonparser.getText();
        try {
            return LocalDate.parse(date, formatter);
        } catch (DateTimeParseException e) {
            throw new RuntimeException("Your custom exception");
        }
    }
}

使用它:

@JsonDeserialize(using = CustomDateDeserializer.class)
LocalDate dateOfBirth;

答案 2 :(得分:0)

这样的事情。

@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