Notes
Introduction
This article explains the specification of Java Bean Validation's @Pattern.
I keep seeing many explanations that use incorrect examples, and reviewing code that references them is exhausting,
so I decided to stop expecting the world to provide correct information and to publish it myself.
The recent article is also part of that effort.
TL;DR
- You do not need to add
^at the beginning and$at the end of the regular expression specified in@Pattern'sregexp - Read the docs and confirm the specification
- Do not blindly trust personal blogs, Qiita, or Zenn (self-contradiction)
Incorrect implementation
If you search Google for how to apply regex validation with the @Pattern annotation in Spring Boot requests, you often see examples like this.
You can find examples that use both ^ and $, or only one of them, but they write regex for @Pattern's regexp in the form ^<regex>$.
This works and is not incorrect, but you do not need to use ^ and $.
People who deliberately add ^ and $ may not understand the @Pattern specification.
Jakarta Bean Validation
If you want to implement validation in Java, it is common to use a library compliant with Jakarta Bean Validation. Jakarta Bean Validation is the specification for Bean Validation, transferred from JSR 303, JSR 349, and JSR 380, and managed by the Eclipse Foundation. 1
In Java, there are cases where only the specification is defined independently, and multiple libraries implement it. For example, Hibernate Validator is the reference implementation for Jakarta Bean Validation. Hibernate Validator is commonly used, but there is also Apache BVal as a Jakarta Bean Validation-compliant implementation.
Hibernate Validator
PatternValidator
Validation for the @Pattern annotation is performed by PatternValidator.
Whether validation succeeds is determined by the Matcher#matches method.
Matcher#matches checks whether the entire string matches the regular expression.
If only part of the string matches, validation fails.
Therefore, for the @Pattern annotation, validation succeeds if the entire string matches the regex even without ^ and $.
Correct (?) implementation
Even though adding ^ and $ does not change behavior, it is just noise, so it should be avoided.
Thus the earlier example can be rewritten like this.
Conclusion
When specifying a regular expression for @Pattern's regexp, you do not need to add ^ and $.
Older articles do not use ^$, but many recent articles seem to add them.
At some point incorrect information was written, and many people likely use code they find online as-is. Do not blindly trust information found online; it is important to read official documentation and confirm the specification.
Footnotes
-
For Java EE and Jakarta EE, see From Java EE to Jakarta EE. ↩

