Imran
Imran

Reputation: 6235

Spring Java Date to Date Pattern Validation

I have Spring Rest Service Payload Object with Date inside it.

Now I would like to throw Parsing or Validation Exception if the Date passed is not in yyyy-MM-dd format. Example - if they 12-01-2016, I want to throw exception except for 2016-12-01. Please advise

Note - I am trying parse Date directly here using getDob and I have seen lot of examples which are parsing String.

public class PayLoad {
    private Date dob = null;
    @JsonFormat(pattern = "yyyy-MM-dd")
    public Date getDob() {
        return dob;
    }
    @JsonFormat(pattern = "yyyy-MM-dd")
    public void setDob(Date dob) {
        this.dob = dob;
    }
}

Upvotes: 1

Views: 4126

Answers (1)

massfords
massfords

Reputation: 729

First, I wouldn't model a date of birth as a java.util.Date. You should use java.time.LocalDate.

Second, you probably need a custom JsonSerializer/JsonDeserializer here if you're using Jackson. That should be trivial to write. Here's an example.

Upvotes: 2

Related Questions