javaspringspring-bootbean-validationjsr

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": "eerwer@gmail.com","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


Solution

  • 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));
    
    }
    }