Regex Validation not triggering an Error in Spring Boot Controller

Patrick Felbauer :

I want my RestController to return an error when the input of date is set(required = false) but with the wrong regex(f. e. 10-2019)

  @GetMapping
  @Timed
  public ResponseEntity<ResponseBodyWrapper<List<ListData>>> getList(
     @RequestParam(name = "date", required = false) @Pattern(regexp = "[0-9]{4}-[0-9]{1,2}") String date) {
    // Logic
  }

However, the validation isnt taking place. I was expecting an error but none was thrown, the error occured later, when i tried to build a new Object with the wrong input

cassiomolin :

Fix the validation with @Validated

When you want the validation to be triggered, the controller class must be annotated with @Validated:

@Validated
@RestController
public class MyController {
   ...
}

Quoting the documentation:

To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation.

Don't use @Timed

I find it weird the fact your controller method is annotated with @Timed. This is a test-specific annotation and it's not meant to be used in the actual code:

Test-specific annotation to indicate that a test method has to finish execution in a specified time period.

You may also want to review your dependencies and ensure they use the correct scope.

Consider YearMonth instead of String

As you seem to be receiving a year and month value in your controller method, it's better to use YearMonth instead of String:

A year-month in the ISO-8601 calendar system, such as 2007-12.

Your controller method can be like:

@GetMapping
public ResponseEntity<Foo> getList(@RequestParam(name = "date", required = false) YearMonth date) {
    ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163869&siteId=1