Card 05/ 06
Practice: Adding a Pattern Constraint to a Request Field
A vehicle type that must be sedan, suv or van, and the annotation that enforces it.
@Pattern constrains a String to match a regular expression (a pattern that describes which text is allowed). RideRequest is a record with two constrained fields, @NotBlank String pickup and @Min(1) int passengers, and a controller that accepts it with @Valid, which checks the constraints before the method runs. It needs a third field, vehicleType, that must be one of "sedan", "suv" or "van". Write the field with its constraint, including a message a client could act on. Then say what happens when a request arrives with "truck", before you open the answer.
See the answer
@Pattern(regexp = "^(sedan|suv|van)$", message = "Invalid vehicle type")
String vehicleTypesedan|suv|van matches any one of the three words. @Pattern checks the whole value, so the ^ and $ anchors are not strictly needed, but they make the intent plain to a reader.
One more thing: a null vehicle type passes @Pattern, because Bean Validation, the standard behind these constraint annotations, treats null as valid for every constraint except @NotNull and its relatives. If the field is required, add @NotNull as well.
A request with "truck" fails the pattern, so @Valid rejects it with MethodArgumentNotValidException carrying one field error, for vehicleType, with your message.
← → move through sections and cards