Validate that Java LocalDate matches yyyy-MM-dd format with readable message
Asked Answered
H

3

5

I have below property in POJO class for DoB.

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

How can I validate that

  1. User is sending valid date format (accepting only YYYY-MM-DD)
  2. If user enters incorrect date I want to send custom message or more readable message. Currently if user entered invalid date then application sends below long error -
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; 
...
Hayner answered 5/8, 2019 at 23:6 Comment(0)
R
4

You can use this annotation:

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

You can read further about custom error messages when validating date format in here: custom error message

Rutaceous answered 6/8, 2019 at 4:38 Comment(0)
O
0

You should create your custom deserializer, overwrite deserialize method to throw your custom error and use it in @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");
        }
    }
}

Use it:

@JsonDeserialize(using = CustomDateDeserializer.class)
LocalDate dateOfBirth;
Orel answered 6/8, 2019 at 22:21 Comment(1)
Your format should be yyyy-MM-dd or uuuu-MM-dd. Check the documentation to learn the difference between Y and y, and between D and d.Boult
S
0

Something like this.

@Column(name = "date_of_birth")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE)
@JsonFormat(pattern = "YYYY-MM-dd")
private LocalDateTime dateOfBirth;

DateTimeFormatter Java doc

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Surefooted answered 7/8, 2019 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.