pm1090
pm1090

Reputation: 101

constraint validation on @RequestParam does not seems to be working

I have a GetAll operation that pull all employees in a deptNo. I want to add a constraint that checks the size on deptNumber on my RequestParameter but it doesn't seems to be validating the parameter. How can I achieve the validation?

    public ResponseEntity<PagedResources<EmpSummary>> getEmps(
@Valid @RequestParam @Max(1) @Max(999) Optional<Long> deptNUmber)

@Controller
@Validated
@RequestMapping("/v1")
@RequiredArgsConstructor
public class OntApiController implements OntApi {
    private final OntService service;
    private NativeWebRequest    nativeWebRequest;
    private HttpServletRequest  httpServletRequest;

    @Override
    public ResponseEntity<PagedResources<OntSummaryResource>> getOnts(
            @Valid @RequestParam @Min(1L) @Max(999L) Optional<Long> ontNumber,
            @Valid @RequestParam @Min(1) @Max(999) Optional<Integer> model,
            ...... more parameters);

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Max' validating type 'java.util.Optional'. Check configuration for

    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>

Upvotes: 2

Views: 1227

Answers (1)

Sai prateek
Sai prateek

Reputation: 11926

As per documentation : You should add annotation @Validated to your controller, if you're using method argument validation.

Now your code would be like this:

@RestController
@RequestMapping("/your_api")
@Validated
public class YourController {

   @GetMapping("/your_endpoint")
   public ResponseEntity> getEmps(
     @RequestParam @Min(1) @Max(999) Optional deptNUmber){

Upvotes: 1

Related Questions