Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Validation not triggering an Error in Spring Boot Controller

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

like image 662
Felpower Avatar asked Sep 12 '19 08:09

Felpower


2 Answers

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) {
    ...
}
like image 136
cassiomolin Avatar answered Nov 06 '22 12:11

cassiomolin


You need to add the @Validated annotation to the class:

@RestController
@Validated
public class myRestController{

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

References: https://www.baeldung.com/javax-validation-method-constraints point 3.

like image 2
Vicent Morera Orchilles Avatar answered Nov 06 '22 11:11

Vicent Morera Orchilles