Home > Net >  Validate a date received in String
Validate a date received in String

Time:08-25

When the request is made by Postman, I need to check if the received date is valid in the "yyyy-mm-dd" format and then send it to my Service. Is there any way to do this with String?

Example:

My Controller:

@GetMapping("/by-date")
public ResponseEntity<List<ResponseRet>> getByDate(@RequestParam(required = false) String dateGte,
                                                              @RequestParam(required = false) String dateLte) {
    List<ResponseRet> responseRet = searchService.findByDate(dateGte, dateLte);
    return ResponseEntity.ok(responseRet);
}

In this case I would need to do this check in the Controller or in the Service

CodePudding user response:

In your service class you can try to parse String into LocalDate:

public List<ResponseRet> findByDate(String dateGte, String dateLte) {
    try {
        LocalDate.parse(dateGte);
        LocalDate.parse(dateLte);
    } catch (DateTimeParseException ex) {
        // log, throw your custom exception with 400 http response code or whatever
    }
    // other code;
}

While parsing, LocalDate is using default DateTimeFormatter.ISO_LOCAL_DATE - dates like "2022-08-24".
If you want to parse with other format, create instance of DateTimeFormatter and use it:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/mm/dd");
LocalDate.parse(dateGte, formatter);

Also you can change your method's arguments type to LocalDate and do validation on the controller level:

@GetMapping("/by-date")
public ResponseEntity<List<ResponseRet>> getByDate(
                       @RequestParam(required = false) @Valid @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate dateGte,
                       @RequestParam(required = false) @Valid @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate dateLte) {
    List<ResponseRet> responseRet = searchService.findByDate(dateGte.toString(), dateLte.toString());
    return ResponseEntity.ok(responseRet);
}
  • Related