@NotBlank does not triggers on empty string or null

39 Views Asked by At

I have Spring @RestController controller with method:

@PostMapping(path = [CONTROLLER_PATH])
fun post(
    @RequestBody(required = true) @Valid sendSmsTask: Request,
) : String {
    return UUID.randomUUID().toString()
}

Request model:

import jakarta.validation.constraints.NotBlank

data class Request (
    @NotBlank
    val receiverNumberPhone: String?,

    @NotBlank
    val text: String?
)

Then I try to send invalid request body:

{
    "receiverNumberPhone": "",
    "text": null
}

Expected: return 422 with 2 validation errors

Actual: return 200 with UUID.

Why @NotEmpty does not trigger validation errors?

Dependencies from build.gradle.kts:

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-mail")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-validation")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}
1

There are 1 best solutions below

0
On

In data classes validation annotation must be written with @field: prefix:

import jakarta.validation.constraints.NotBlank

data class Request (
    @field:NotBlank
    val receiverNumberPhone: String?,

    @field:NotBlank
    val text: String?
)