I need to validate date using jsr annotations / spring rest
@Email(regexp = ".+@.+\\..+")
private String email;
@NotNull
@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate dateOfBirth;
But its accepting below json request
{ "email": "[email protected]","dateOfBirth": 7,}
and its parsing the date as 1970-01-07 (adding 7 days from 1970)
even below annotation is allowing numbers
 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
How can I invalidate this request
An alternative:
Notice that LocalDateDeserializer and LocalDateTimeDeserializer support internally leniency features.
That being said, a clean solution that you can make available through a Bean:
@Bean
ObjectMapper objectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();
    // make sure you added jackson-datatype-jsr310 dependency
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    // option 1
    objectMapper.setDefaultLeniency(FALSE);
    // option 2
    objectMapper.configOverride(LocalDate.class).setFormat(JsonFormat.Value.forLeniency(FALSE));
    objectMapper.configOverride(LocalDateTime.class).setFormat(JsonFormat.Value.forLeniency(FALSE));
    return objectMapper;
}
Another in-place alternative could be:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", lenient = OptBoolean.FALSE)
on the field/method itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With