Java - How to make JSON date validation?

Dvir picture Dvir · Dec 25, 2017 · Viewed 7.9k times · Source

I have this piece of code:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    protected Date statusDate;

But for somehow it accepts date formats like -

"statusDate": "2017-13-27"

or

"statusDate": "201823-12-12"

Is it possible to validate the format within the request (not manually)?

Answer

Olantobi picture Olantobi · Dec 25, 2017

@JsonFormat is used to set the output format when you're returning the statusDate as response.

It is better you create a DTO object that will accept String statusDate and then convert it to Date format in your controller.

To validate the date in String format, you can use @Pattern

public class StatusDateDto {

    @NotNull(message="Status date is a required field")    
    @Pattern(regexp = "^\\d{4}-\\d{2}-\\d{2}", message="Invalid status date")
    private String statusDate;

    //Getter and setter
}

public ResponseEntity<?> postStatusDate(@Valid @RequestBody StatusDateDto dateDto, BindingResult result) {

        if (result.hasFieldErrors()) {
            String errors = result.getFieldErrors().stream()
                .map(p -> p.getDefaultMessage()).collect(Collectors.joining("\n"));   

            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
        }

        // Convert the String to Date after validation

        return ResponseEntity.ok().build();
    }