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; 
...
M. Justin
  • 14,487
  • 7
  • 91
  • 130
ppb
  • 2,299
  • 4
  • 43
  • 75

3 Answers3

2

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

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;
Dorin Simion
  • 131
  • 5
  • Your format should be `yyyy-MM-dd` or `uuuu-MM-dd`. Check the [documentation](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) to learn the difference between `Y` and `y`, and between `D` and `d`. – Arvind Kumar Avinash Jul 24 '21 at 21:07
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

Dinesh K
  • 269
  • 2
  • 8