Required Text with @NotBlank
@NotBlank marks text that must not be blank. A blank title fails the check.
A title must not be blank
The message names the problem when the check fails.
public record TaskForm(
@NotBlank(message = "Title must not be blank") String title,
boolean done) {
}Example
package com.example.demo;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TaskController {
private final TaskRepository repository;
public TaskController(TaskRepository repository) {
this.repository = repository;
}
@PostMapping("/tasks")
public ResponseEntity<TaskView> createTask(@Valid @RequestBody TaskForm form) {
Task task = new Task(form.title(), form.done());
repository.save(task);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new TaskView(task.getTitle(), task.isDone()));
}
public record TaskForm(
@NotBlank(message = "Title must not be blank") String title,
boolean done) {
}
public record TaskView(String title, boolean done) {
}
}Key points
- @NotBlank sits on a String field.
- Blank means empty or only spaces.
- A title of spaces fails the check.
- A real title passes the check.
- The check runs when @Valid is present.
- The message names the problem.
In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The TaskForm record marks the title with @NotBlank, so it must hold real text. The createTask method marks the body with @Valid, so Spring checks it first. A title of three spaces is rejected with 400. A real title is saved and answered with 201.
Note
@NotBlank checks text, so it never sits on a number.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which title fails @NotBlank?