1

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?

3
  • 2
    Replace @Min(value= 5)(and the other validation annotations too, of course) by @field:Min(value= 5). Commented Jul 27, 2019 at 7:02
  • @JBNizet Yes, it worked! Thanks! However I still don't understand how this could be a difference. Any clues? Commented Jul 27, 2019 at 16:30
  • 1
    If you don't specify @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. Commented Jul 27, 2019 at 16:34

1 Answer 1

3

From @JBNizet comment

Replace @Min(value= 5) (and the other validation annotations too, of course) by @field:Min(value= 5).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.