Apply regex constraints with Hibernate Validator
How the @Pattern constraint works in Hibernate Validator: what it checks, what it never changes, and how Unicode, null and copied text affect results.
Hibernate Validator is the reference implementation of Jakarta Bean Validation, and its main tool for regular expressions is the @Pattern constraint. This review explains what @Pattern does, where it fits in a text-handling workflow, and where it can give misleading results. One point matters throughout: a regex constraint validates text. It does not transform it. No supplied test data or version-specific measurements were available for this article, so the behavior below is based on the documented specification and the semantics of the java.util.regex engine. Check the details against the documentation for the Hibernate Validator version you use.
Is a regex constraint suitable for your use?
Use @Pattern when a string field must follow a fixed, machine-checkable format. Good examples are usernames limited to a known character set, postal codes, product SKUs and internal identifiers. The main benefit is that the rule sits on the field declaration, so every layer that validates the bean applies the same rule. The decisive tradeoff is that a pattern only says yes or no. It does not clean, normalize or repair input, and it can reject valid human text that the pattern author did not anticipate.
An unconstrained or loosely constrained plain-text field is the better choice for free-form human input, such as personal names, addresses, comments and titles. Strict character classes on these fields tend to reject legitimate accented, non-Latin or decomposed characters. For these fields, a length limit plus a check for control or formatting characters is usually safer than a tight whitelist pattern.
What @Pattern actually changes
@Pattern does not change stored characters. It reverses nothing, mirrors nothing, substitutes no characters and applies no formatting. The value you validate is the value you persist or process. If you want to trim whitespace, change case or apply Unicode normalization, do it before validation, for example in a setter, a mapping layer or an input-binding step. Hibernate Validator will not do it for you.
The mechanism works like this. The validator compiles the regexp attribute with java.util.regex.Pattern and tests the whole value with a full match. A partial match is not enough, so the expression behaves as though it were anchored at both ends, and you do not need to add ^ and $. The constraint applies to CharSequence values. A null value counts as valid, so pair @Pattern with @NotNull or @NotBlank when the field is required. An empty string is not treated as null. It is tested against the pattern like any other value.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public class Account {
@NotBlank
@Pattern(regexp = "[a-z0-9_]{3,20}",
message = "{account.username.pattern}")
private String username;
@Pattern(regexp = "\\d{5}(-\\d{4})?")
private String zipCode;
}
Two details in this example cause frequent mistakes. First, backslashes must be doubled inside a Java string literal, so the regex \d is written as "\d" in the annotation. Second, older code imports the constraint from javax.validation.constraints, while current Jakarta-based releases use jakarta.validation.constraints. Mixing the two namespaces in one project is a common reason a constraint seems to be silently ignored.
Flags, multiple patterns and programmatic checks
The flags attribute accepts values from the Pattern.Flag enum: UNIX_LINES, CASE_INSENSITIVE, COMMENTS, MULTILINE, DOTALL, UNICODE_CASE and CANON_EQ. UNICODE_CHARACTER_CLASS is not in that enum. If you need it, use the embedded flag (?U) at the start of the expression. To enforce several independent patterns on one field, often with a different message for each, wrap them in @Pattern.List.
@Pattern.List({
@Pattern(regexp = ".*[A-Z].*", message = "{password.uppercase}"),
@Pattern(regexp = ".*\\d.*", message = "{password.digit}")
})
private String password;
@Pattern(regexp = "[a-z]+", flags = Pattern.Flag.CASE_INSENSITIVE)
private String code;
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Account>> violations = validator.validate(account);
violations.forEach(v ->
System.out.println(v.getPropertyPath() + ": " + v.getMessage()));
Unicode, combining marks and stylized text
Most surprises come from the gap between what a reader sees and the code points that are actually stored. Text that looks identical can be encoded in several ways. The letter é can be stored as one precomposed code point or as a plain e followed by a combining acute accent. Stylized "font" text produced by Unicode styling tools is not formatting at all. It uses separate code points, such as the Mathematical Alphanumeric Symbols block. A pattern judges code points, not appearance.
The table compares two patterns on several inputs. The outcomes follow from documented regex and constraint semantics. They are not results from a recorded test run in a specific version, so confirm them in your own test suite.
| Input | [A-Za-z]+ | [\p{L}\p{M}]+ |
| Ada | valid | valid |
| José with precomposed é | invalid | valid |
| José with e plus combining accent | invalid | valid (the accent matches \p{M}) |
| Mathematical bold 𝐀𝐝𝐚 | invalid | valid (these are letter code points) |
| Ada containing a right-to-left override character | invalid | invalid (the override is a format character) |
| Empty string | invalid | invalid |
| null | valid (null is skipped) | valid (null is skipped) |
The table shows the core tradeoff. A narrow ASCII class rejects real names. A broad Unicode letter class accepts real names but also accepts stylized look-alike text, which will not match ordinary searches for the same word. If stylized or look-alike characters are a problem for your data, normalize the input first (NFKC folds many compatibility characters to their plain forms) and validate the result. Then decide whether to store the normalized form. The CANON_EQ flag relates to canonical equivalence, but explicit normalization before validation is easier to reason about and to test.
Length has a similar trap. java.util.regex quantifiers count code points, while @Size on a String counts UTF-16 units through length(). Characters outside the Basic Multilingual Plane, including most emoji and the mathematical styled letters, therefore count as two units under @Size. An emoji built from several code points, such as a family or flag sequence, counts as more still. Reversal and mirroring do not apply here, because the constraint never reorders characters. Grapheme clusters only matter for how lengths and quantifiers are counted.
Readability and usability after copying or sharing
Because @Pattern stores nothing new, values that pass validation copy, paste, search and edit like any other string. Usability problems usually come from what users paste in and from how rejections are reported:
- Pasted input can carry invisible characters such as non-breaking spaces, zero-width characters or bidirectional controls. A strict pattern rejects these with no visible reason, so trim or normalize at the input boundary and say in the message what is allowed.
- The default message has the form must match "{regexp}", which exposes the raw expression. Most readers cannot interpret a regex, so supply a plain-language message through a resource bundle key.
- Hibernate Validator only produces violation objects. Accessible error display, such as linking a message to its field so assistive technology announces it, belongs to the UI layer. No evidence was supplied about how any particular framework or screen reader presents these messages, so test that behavior in your own stack.
- If you accept broad Unicode classes, consider also keeping a plain-text or normalized copy for search and sorting, since stylized characters will not match plain-text queries.
Safety considerations for patterns on user input
Patterns run against untrusted input, so avoid constructions that can backtrack catastrophically, such as nested quantifiers like (a+)+ on long strings. Put a length limit on the field so the regex never sees unbounded input. Treat the pattern as a format check, not a security boundary. Output encoding and parameterized queries are still needed downstream.
Gaps and what to verify
No version-specific evidence, benchmarks or rendering tests were supplied for this review. Before relying on the behavior above, confirm the following against your Hibernate Validator version and environment: the constraint namespace your project uses, the exact default message text, how your UI framework displays violations to assistive technology, and the outcomes in the Unicode table. A short parameterized unit test covering precomposed, decomposed, stylized, empty and null inputs is enough to settle each of these.