kevin_Aberathna
kevin_Aberathna

Reputation: 471

Spring boot with Jackson Unable to Validate java.util.Date

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.

Upvotes: 1

Views: 1354

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

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)

Upvotes: 3

Related Questions