🎓 A1Learner
🔍
0 of 50 lessons completed

Validating Numbers

Validating numbers checks a number against a range. A range takes its lowest value from @Min and its highest value from @Max.

A number with a range

@Min sets the lowest value. @Max sets the highest value.

public record TaskForm(
        @NotBlank(message = "Title must not be blank") String title,
        boolean done,
        @Min(value = 1, message = "Priority must be between 1 and 5")
        @Max(value = 5, message = "Priority must be between 1 and 5") int priority) {
}

Example

package com.example.demo;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
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<?> createTask(@Valid @RequestBody TaskForm form, BindingResult result) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            result.getFieldErrors().forEach(error ->
                    errors.put(error.getField(), error.getDefaultMessage()));
            return ResponseEntity.badRequest().body(errors);
        }
        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,
            @Min(value = 1, message = "Priority must be between 1 and 5")
            @Max(value = 5, message = "Priority must be between 1 and 5") int priority) {
    }

    public record TaskView(String title, boolean done) {
    }
}

Key points

  • Priority is a number that says how urgent a task is.
  • @Min sits on a number field.
  • @Max sits on a number field.
  • A priority below 1 fails the check.
  • A priority above 5 fails the check.
  • A priority from 1 to 5 passes the check.
  • The check runs with @Valid, like the text checks.

In this example, TaskController holds the repository in a field. The constructor receives the repository when Spring builds the controller. The TaskForm record adds a priority field with @Min(1) and @Max(5). The createTask method takes a BindingResult right after the @Valid body. A priority of 9 fails the range, so the error map names the priority field. A priority of 3 passes, so the task is saved and answered with 201.

Note

@Min and @Max check numbers, so they never sit on text.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which priority passes @Min(1) @Max(5)?