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
@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.
@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.
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) {
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With