Reputation: 392
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
Upvotes: 4
Views: 2124
Reputation: 243
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
Upvotes: 2
Reputation: 392
Ended up writing my own deserializer
class LocalDateDeserializer extends StdDeserializer<LocalDate> {
protected LocalDateDeserializer(){
super(LocalDate.class);
}
@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
return LocalDate.parse(jp.readValueAs(String.class));
}
}
Upvotes: 1
Reputation: 2503
Validate date using jsr notationspring rest.
Add dependency
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Entity field like this.
@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate expireDate;
Json request like this.
{
"expireDate" :"2015-01-01"
}
Upvotes: 0