Skip to lesson

Practice: validation

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most validation bugs compile without an error: a constraint on the wrong type, a missing value that passes, validation that never runs, and a rule in the wrong layer. Each needs a habit or a test.

Mistake 1: a constraint on the wrong type

These mistakes compile without a warning. The example puts @NotBlank and @Size on an Integer and then validates it.

Example 1 · Mistake: @NotBlank and @Size on an Integer

Runs in: the validation-lab practice project (Spring Boot 4.1)

BrokenSeatBooking.javaJava
package com.shoplite.lab.l1p;
import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.Size;
// Two wrong annotations: @NotBlank and @Size are for text, not for numbersrecord SeatBooking(        @NotBlank String movie,        @NotBlank @Size(min = 1, max = 10) Integer seats) {}
public class BrokenSeatBooking {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();            System.out.println(validator.validate(new SeatBooking("Jawan", 4)).size() + " problem(s)");        }    }}
Sample output (shortened)
11:12:13.068 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
Exception in thread "main" jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.NotBlank' validating type 'java.lang.Integer'. Check configuration for 'seats'
	at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getExceptionForNullValidator(ConstraintTree.java:99)
	...

What this code does

  • The program compiles, then the first validate call throws UnexpectedTypeException for @NotBlank on Integer; @Size on Integer would fail the same way.
  • Fix: @NotNull @Min(1) @Max(10) Integer seats. The fixed version is practice 4 of the annotations lesson.

Constraint annotations compile on any field, so @NotBlank Integer seats or @Size(min = 1, max = 10) Integer seats look fine in review. At the first validate, Hibernate Validator finds no checker for that pair and throws UnexpectedTypeException (HV000030); in a web app every request to that endpoint becomes a 500.

The fix is to match annotation and type: text gets @NotBlank, @Size, @Pattern, @Email; whole numbers get @NotNull, @Min, @Max, @Positive; BigDecimal gets @DecimalMin, @DecimalMax, @Digits; collections get @NotEmpty and @Size.

Mistake 2: forgetting that a missing value passes

For most constraints a missing value is not an error. The example validates three inputs where "", null and spaces slip through.

Example 2 · Mistake: assuming null, "" and spaces fail

Runs in: the validation-lab practice project (Spring Boot 4.1)

TrickyRulesDemo.javaJava
package com.shoplite.lab.l1p;
import java.math.BigDecimal;
import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Email;import jakarta.validation.constraints.Pattern;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.Size;
record Tricky(        @Email String email,        @Pattern(regexp = "^[0-9]{6}$") String pincode,        @Size(min = 2) String city,        @Positive Integer quantity,        @DecimalMin("0.00") BigDecimal discount) {}
public class TrickyRulesDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();            print(validator, "A", new Tricky("", null, "  ", 1, new BigDecimal("0.00")));            print(validator, "B", new Tricky("ravi@college", "56003", "Pune", 0, null));            print(validator, "C", new Tricky(null, "560038", "P", null, new BigDecimal("-0.01")));        }    }
    static void print(Validator validator, String label, Tricky input) {        var fields = validator.validate(input).stream()                .map(v -> v.getPropertyPath().toString())                .sorted()                .toList();        System.out.println(label + ": " + (fields.isEmpty() ? "valid" : "invalid " + fields));    }}
Sample output
11:12:27.590 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
A: valid
B: invalid [pincode, quantity]
C: invalid [city, discount]

What this code does

  • Input A is valid although the e-mail is "", the pincode is null and the city is two spaces: none of those constraints checks for "missing".
  • Input C shows the inclusive default of @DecimalMin("0.00"): -0.01 fails, but 0.00 in input A passes.

Every constraint except @NotNull, @NotEmpty and @NotBlank treats null as valid. @Email String email accepts a request with no e-mail, @Positive Integer quantity accepts no quantity, and @Pattern accepts null. Some also accept surprising values: @Email passes "", and @Size(min = 2) counts spaces.

So every field needs two decisions: is it required (add a null check), and what must it look like (add the format constraint). Trimming in the compact constructor stops spaces from passing length rules.

Predict the output

Does it pass?

Read the record and the value, then pick the number of violations.

Round 1 of 3

record Contact(@Email String email) { }
validator.validate(new Contact(null)).size()

Mistake 3: validation that never runs

Constraints are only descriptions until something calls the Validator. The example has @Valid on the body, but also a BindingResult that nobody reads.

Example 3 · Mistake: a BindingResult that nobody reads

Runs in: the validation-lab practice project (Spring Boot 4.1)

SilentProductController.javaJava
package com.shoplite.lab.l2p;
import com.shoplite.lab.product.CreateProductRequest;
import jakarta.validation.Valid;
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;
// Bug: a BindingResult parameter collects the errors, so Spring no longer throws, and nobody reads it@RestControllerpublic class SilentProductController {
    @PostMapping("/lab/silent/products")    public ResponseEntity<String> create(@Valid @RequestBody CreateProductRequest request, BindingResult errors) {        return ResponseEntity.status(201).body("saved " + request.sku());    }}
Sample output
$ curl -i -X POST http://localhost:8080/lab/silent/products -H "Content-Type: application/json" -d '{"sku": "kb 1", "name": "K", "categoryId": 4, "price": -5.00}'
HTTP/1.1 201
Content-Type: text/plain;charset=UTF-8

saved kb 1

What this code does

  • @Valid is there, but the BindingResult parameter tells Spring that the method handles errors itself. It does not, so the contract's bad product is "saved" with 201.
  • Fix: remove the parameter (the @Valid lesson's practice 6 shows the 400 that follows).

Constraints are only descriptions until something calls the Validator. Three ways to switch it off by accident: no @Valid on a @RequestBody, no @Valid on a nested list's element type, and a BindingResult parameter that nobody reads (Spring stops throwing when one is present).

The symptom is the same each time: bad data saved with 201, or a 500 from deep inside the service, and no WARN line. One controller test per endpoint that sends a bad body and expects 400 catches all three.

Mistake 4: the old @Validated style and rules in the wrong layer

@Validated on a controller class turns a client's typo into a server error. The example shows a bad id answered with a 500.

Example 4 · Mistake: @Validated on a controller class

Runs in: the validation-lab practice project (Spring Boot 4.1)

ProductQueryController.javaJava
package com.shoplite.lab.product;
import java.math.BigDecimal;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;
import org.springframework.http.ResponseEntity;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
@Validated // the older style: validation through a Spring proxy@RestController@RequestMapping("/api/v1/products")public class ProductQueryController {
    private final ProductService productService;
    public ProductQueryController(ProductService productService) {        this.productService = productService;    }
    @GetMapping("/{id}")    public ResponseEntity<ProductResponse> getById(            @PathVariable @Positive(message = "must be a positive id") long id) {        return ResponseEntity.of(productService.findById(id));    }
    @GetMapping    public PageResponse<ProductResponse> list(            @RequestParam(required = false)            @DecimalMin(value = "0.00", message = "must be 0 or more") BigDecimal minPrice,            @RequestParam(defaultValue = "0")            @PositiveOrZero(message = "must be 0 or more") int page,            @RequestParam(defaultValue = "20")            @Min(value = 1, message = "must be between 1 and 100")            @Max(value = 100, message = "must be between 1 and 100") int size) {        long total = productService.search(minPrice, null).count();        return PageResponse.of(productService.page(minPrice, null, page, size), page, size, total);    }}
Sample output
$ curl -i http://localhost:8080/api/v1/products/0
HTTP/1.1 500
Content-Type: application/json

{"timestamp":"2026-10-16T05:04:17.863Z","status":500,"error":"Internal Server Error","path":"/api/v1/products/0"}

Server console (shortened):
2026-10-16T10:34:17.836+05:30 ERROR 5880 --- [validation-lab] [io-18613-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: jakarta.validation.ConstraintViolationException: getById.id: must be a positive id] with  ...

What this code does

  • A bad id is the client's mistake, yet the client gets 500 and the log gets an ERROR with a stack trace.
  • Removing @Validated lets Spring MVC's built-in method validation answer 400 through HandlerMethodValidationException.

@Validated on a controller class switches parameter checks to an older proxy that throws ConstraintViolationException, which becomes a 500 instead of a 400. In Spring Boot 3.2+ and 4.x, leave it off controllers: constraints on @PathVariable and @RequestParam are checked anyway.

The opposite mistake is putting data rules into annotations (@UniqueSku calling a repository) or into controllers (if (repository.existsBySku(...))). Data rules belong in the service, which throws meaningful exceptions in the contract's order: 404, 422, 409.

Finish up

Mark complete & continue

Next: Mini project: ShopLite input validation