1

I need to validate date with pattern 'yyyy-MM-dd HH:mm:ss'. I'm using util date with jackson version 2.10.2 and I can't move to java 8 localdate as company requirement. I found many Q&A regarding this issue and none of them solve my problem properly.

import com.fasterxml.jackson.annotation.*; import lombok.Data; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "provisionedDate", }) @Data @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) public class PostProvisionCallback implements Serializable { @JsonProperty("id") private String id; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") @NotNull(message = "provisionedDate cannot be null") @JsonProperty("provisionedDate") private Date provisionedDate; } 

even I enter invalid date like '20201-0612213-17 09:26:12',still this is evaluate as valid date. What is the perfect solution for this.? but if I enter date as '2020/03/04 09:26:12' then application throw internal server error exception.

1
  • I recommend you don’t use Date. That class is poorly designed and long outdated. Instead use LocalDateTime or some other class from java.time, the modern Java date and time API. Commented Oct 26, 2020 at 3:38

1 Answer 1

3

It is the SimpleDateFormat that handles the actual configurable parsing. You can set the value of lenient as false.

Replace

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") 

with

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.