I'm trying to use javax constraints to pre-validate a request content before running the logic.
I have tried any possible solution out there but still can't put javax annotations to work in a Spring boot.
import javax.validation.constraints.Min
import javax.validation.constraints.Pattern
data class LoginRequest (
@Credential //Custom constraint that works just fine
val credential: String,
@Min(value= 5)
val password: String,
@Pattern(regexp = Constants.Regex.DEVICE_ID_REGEX, message = "Invalid device ID")
val device: String
): Serializable
This is a part of pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
.
.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.17.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.0.17.Final</version>
</dependency>
And this is the controller
import javax.validation.Valid
@PostMapping("/login")
fun userLoginEndpoint(@Valid @RequestBody loginRequest: LoginRequest): ResponseEntity<User> {
return authService.loginUser(loginRequest)
?.let{ ResponseEntity(it, HttpStatus.ACCEPTED)}
?: ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()
}
Am I doing something wrong?
@Min(value= 5)(and the other validation annotations too, of course) by@field:Min(value= 5).@field, then what is annotated is the constructor argument AFAIK. But Spring validates the object, once it has been constructed. So what needs to be annotated is the fields.