[英]@Min and @Max validation is not working of hibernate validator package in spring boot
[英]String max length validation is not working in Spring
在我的一個應用程序中,我有一個端點,我想從中驗證其輸入參數。
此方法接收的參數之一是字符串,我嘗試設置它的最大長度,但它不起作用。 當我使用超過 100 個字符的字符串調用端點時,我可以毫無問題地進行調用,並且不應該被允許
問題是我需要以盡可能少的更改執行此驗證,因為此方法是從我不管理的其他應用程序調用的,並且執行任何類型的修改都會很昂貴:將屬性合並到 bean
@SecuredApi(securityLevels = {SecuredApiLevel.COMPANY, SecuredApiLevel.USER})
@GetMapping("/example")
public ResponseEntity<SearchRestDTO> search(
**@Valid @Size(max=100)** @RequestParam(value = "query") @ApiParam(required = true, value = "The query that is searched") String query,
return new ResponseEntity<>(searchService.search(query)), HttpStatus.OK);
}
在 class 級別上,使用@Validated
,然后使用@Valid
注釋的驗證應該可以正常工作。
這是經過測試的示例代碼 -
@Validated
@RestController
public class TestController {
@GetMapping("/example")
public ResponseEntity<String> search(
@Valid @Size(max=5) @RequestParam(value = "query") String query) {
return new ResponseEntity<>("String Length is valid.", HttpStatus.OK);
}
}
此外,在您完成 object 驗證之前,不需要 @Valid。
需要以下依賴項 -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.