Validate Spring request parameters with regex

How to validate Spring @RequestParam values with @Pattern regex: setup, error handling by version, Unicode pitfalls, readable messages and when typed binding fits better.

What regex validation of a request parameter actually does

In Spring MVC, a query or form parameter bound with @RequestParam can be checked against a regular expression by adding the Jakarta Bean Validation constraint @Pattern to the same method parameter. This is a gate, not a transformation. The characters your controller receives are exactly the characters that arrived, after Spring has URL-decoded the request. Nothing is trimmed, case-folded, normalized or rewritten. If the value fails the pattern, the request is rejected before your method body runs. If it passes, the method gets the original string unchanged.

That distinction matters when text comes from copy and paste. A value can look correct on screen and still fail. Examples include styled "font" letters from a Unicode generator, a mirrored or upside-down character, an accented letter stored in decomposed form, or an invisible direction-control character. The pattern judges stored code points, not visual appearance. Any cleanup has to be a separate, deliberate step.

Is it the right tool for your parameter?

Regex validation suits short values with a fixed shape: order codes, slugs, SKUs, country or currency codes, and identifiers that follow a house format. The main benefits are that the rule is declared in the method signature next to the parameter, and that failures produce a consistent client error instead of ad hoc checks inside the method.

The decisive tradeoff is that a regex checks shape, not meaning. A pattern for YYYY-MM-DD accepts 2026-02-31. A pattern for a numeric ID accepts an ID that does not exist. Where Java already has a fitting type, typed binding is usually the better choice. That includes Long, UUID, an enum, or LocalDate with @DateTimeFormat, because Spring's conversion rejects malformed input and you receive a usable object. For free text, such as names, search queries and comments, a restrictive pattern like letters-only tends to reject legitimate input. In those cases, accept plain text, cap the length, and handle safety at the point of use.

Setting it up

  • Add the validation starter. Spring Boot's web starter does not include a Bean Validation provider on its own.
  • Put @Pattern, from jakarta.validation.constraints on Spring Boot 3 or javax.validation.constraints on older versions, directly on the @RequestParam parameter.
  • Make sure method validation is active for the controller. See the version notes below.
  • Give the constraint a plain-language message and decide how the error response should look.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
import jakarta.validation.constraints.Pattern;

@RestController
@RequestMapping("/orders")
class OrderController {

    private final OrderService orderService;

    OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping
    List<OrderSummary> find(
            @RequestParam
            @Pattern(regexp = "[A-Z]{2}-\\d{6}",
                     message = "Order code must be two capital letters, a hyphen and six digits, for example AB-123456")
            String code) {
        return orderService.findByCode(code);
    }
}

Three behaviors catch people out. First, @Pattern must match the entire value, because the validator uses a full match rather than a search, so ^ and $ anchors are unnecessary. Second, a null value counts as valid. With @RequestParam(required = false), a missing parameter passes the pattern silently, so add @NotNull or @NotBlank if absence should be an error. Third, a parameter that is present but empty, such as code=, reaches the constraint as an empty string unless a defaultValue is set. A defaultValue replaces both missing and empty values.

How failures surface depends on your Spring version

Spring Framework 6.1 (Spring Boot 3.2 and later) added built-in method validation for controller methods. When a Bean Validation provider is present and constraints sit directly on method parameters, Spring validates them and raises HandlerMethodValidationException. Spring's default exception handling turns that into a 400 response. On earlier versions, the usual approach is to annotate the controller class with @Validated. That routes validation through an AOP proxy, which throws ConstraintViolationException. Without a handler, typically an @ExceptionHandler or @ControllerAdvice mapping it to 400, this tends to surface as a 500 server error. On 6.1 and later, Spring's documentation advises against keeping class-level @Validated alongside the built-in mechanism, since both would apply. Check which path your version uses before relying on a particular status code.

Approach | On mismatch | Good for | Caveat
@RequestParam with @Pattern | 400 via built-in validation (6.1+), or ConstraintViolationException via @Validated on older versions | Fixed-format query and form values | Null passes; needs the validation starter
Typed parameter (Long, UUID, enum, LocalDate) | Conversion failure, reported as a 400 | Values with a natural Java type | Default error text is technical
Regex in a path variable, e.g. {id:\d+} | No handler matches, usually 404 | Path segments | Does not apply to query parameters
Manual check in the method body | Whatever you implement | Rules involving several parameters or lookups | Logic is scattered and easy to skip

Unicode, styled text and lookalike characters

In Java regex, \d, \w and \s are ASCII-only by default, and [A-Za-z] means exactly those 52 letters. To accept letters from any script, use Unicode property classes such as \p{L} for letters and \p{M} for combining marks. Alternatively, prefix the pattern with the inline flag (?U) so the shorthand classes become Unicode-aware. The @Pattern flags attribute does not offer an option for this, so the inline flag is the practical route.

Text produced by "fancy font" generators is usually built from Mathematical Alphanumeric Symbols. These are separate code points that only resemble ordinary letters. They fail [A-Za-z], but they can pass \p{L}, because they are classified as letters. Mirrored and upside-down text generators substitute lookalike characters in a similar way. If a parameter feeds lookups, comparisons or URLs, an ASCII-restricted pattern is the safer default. If it carries human-readable input, accept a wider class deliberately, and remember that a passing value may not compare equal to the plain-text word it imitates.

Accented letters can arrive precomposed, as a single code point, or decomposed, as a base letter followed by a combining mark. A pattern written for one form may reject the other. The CANON_EQ flag lets matching treat canonically equivalent forms as equal. Normalizing with java.text.Normalizer before validation is the more predictable option, but it requires a custom step rather than the annotation alone. Length limits also need care. @Size counts UTF-16 code units, so a single emoji can count as two or more, and an emoji built from several joined code points counts as more still.

Permissive patterns such as .+ also admit invisible characters, including bidirectional overrides and zero-width joiners. These can change how a value displays in logs or admin screens without changing what it appears to say. An explicit allow-list class avoids this.

Copying patterns between a regex tester and Java code

A pattern that works in an online tester can break when pasted into an annotation, for two common reasons. First, Java string literals need every backslash doubled, so \d{6} in a tester becomes "\d{6}" in source code. Second, regex flavors differ. Testers often default to JavaScript or PCRE, which handle some escapes, lookbehind rules and Unicode classes differently from java.util.regex. Set the tester to the Java flavor if it offers one. More reliably, keep the pattern in a constant and cover it with a unit test that uses the same full-match semantics as @Pattern.

static final String ORDER_CODE = "[A-Z]{2}-\\d{6}";

@Test
void orderCodePattern() {
    assertTrue("AB-123456".matches(ORDER_CODE));
    assertFalse("ab-123456".matches(ORDER_CODE));
    assertFalse("AB-12345".matches(ORDER_CODE));
    assertFalse("AB-123456 ".matches(ORDER_CODE));
}

Annotation attributes must be compile-time constants, so the constant can be referenced directly: @Pattern(regexp = ORDER_CODE). The trailing-space case in the test is worth keeping. Values pasted from documents or spreadsheets often carry stray whitespace, and the pattern will reject them unless you trim them first.

Readable error messages and accessibility

Without a custom message, the default constraint message reads roughly as "must match" followed by the raw pattern. That is meaningless to most users, exposes implementation detail, and is awkward when a screen reader reads it aloud, backslashes and brackets included. Write the message attribute in plain language with a concrete example, as in the controller above. Repeat the same format hint next to the input field in the client, so users learn the expected format before submitting. The supplied material contains no testing with specific screen readers or client frameworks, so verify how your error responses are announced in your own interface.

Performance and security limits

Java's regex engine backtracks, so patterns with nested or overlapping quantifiers, such as (a+)+ or (\w|\d)*, can take a very long time on crafted input. Keep request-parameter patterns simple, and bound repetition inside the pattern itself, for example {2,32}, rather than relying on a separate @Size check. Regex validation also narrows input but does not make it safe in every context. Parameterized queries and context-appropriate output encoding are still required wherever the value is used.

Evidence gaps

No version-specific test results, benchmarks or observations from named environments were supplied for this review. The behavior described reflects the documented design of Spring Framework, Spring Boot and Jakarta Bean Validation. Confirm it against the exact versions you run, especially the status code returned on validation failure and whether class-level @Validated is still present in your controllers.