Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormat accepting numbers in json request instead of date format

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

like image 969
hacker Avatar asked Oct 28 '25 10:10

hacker


1 Answers

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

like image 83
migo Avatar answered Oct 31 '25 00:10

migo