@Pattern is a common stumbling block when writing input validation. You write a regular expression, values that should pass get rejected, and then null or an empty string gets through without any trouble.

This article covers only @Pattern (jakarta.validation.constraints.Pattern) in Spring Boot 3.x. It explains how to write regexp, how null is handled, how to use flags and message, gives ready-to-use patterns, and shows how to test them. For an overview that includes the other standard annotations, see the validation annotations cheat sheet.

Start with a Minimal Setup

Add the spring-boot-starter-validation dependency. It also brings in Hibernate Validator and a Jakarta EL implementation.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Put @Pattern on the DTO field and @Valid on the Controller parameter. Import from jakarta, not javax.

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

public record UserRequest(
        @NotBlank
        @Pattern(regexp = "\\d{3}-\\d{4}", message = "郵便番号は123-4567の形式で入力してください")
        String zipCode) {
}

@RestController
@RequestMapping("/users")
class UserController {

    @PostMapping
    ResponseEntity<Void> create(@Valid @RequestBody UserRequest request) {
        return ResponseEntity.ok().build();
    }
}

If the format doesn’t match, a MethodArgumentNotValidException is thrown and a 400 Bad Request is returned by default. For details on how @Valid works, see How to Implement Validation with @Valid. The rest of the code in this article leaves out all but the most important imports.

regexp Must Match the Entire String

This is the most common misunderstanding. Hibernate Validator’s PatternValidator calls Matcher.matches() internally, so regexp must match the whole string. A partial match is not enough.

@Pattern(regexp = "\\d{3}-\\d{4}")    // "123-4567" は OK、"〒123-4567" は NG
@Pattern(regexp = "^\\d{3}-\\d{4}$")  // 上と同じ挙動。^ と $ は不要だが付けても害はない
@Pattern(regexp = ".*admin.*")        // 「admin を含む」にしたいなら前後を .* で囲む

If you write just admin expecting find() behavior, only the exact string “admin” will pass.

Escaping is the other pitfall. The pattern is a Java string literal, so the regex \d becomes "\\d" and \. becomes "\\.". Writing "\d" causes a compile error, so you’ll notice that one right away. The harder bug is writing just . when you meant \\.. It means “any single character,” so unexpected values pass without any error.

Annotation attribute values must also be compile-time constants. Putting your patterns in public static final String constants makes them easier to reuse and read. The pattern collection later in this article does this.

null Passes; Empty Strings Depend on the Pattern

Under the Bean Validation specification, @Pattern treats null as valid. The idea is that null checks belong to other constraints such as @NotNull.

An empty string "", however, is checked against the regex like any other value. \d{3}-\d{4} rejects it, but a pattern that allows zero characters, such as [a-z]*, lets it through.

So for required fields, the usual approach is to add @NotBlank. Note that if an empty string is sent, it violates both @NotBlank and @Pattern, so you get two error messages back.

For an optional field where you want “empty is OK, but check the format if something is entered,” add the empty string as an alternative:

// null は仕様上どのみち通る。^$| を付けると空文字 "" も通るようになる
@Pattern(regexp = "^$|0\\d{9,10}")
String phone;

The flags Attribute and Inline Flags

Use flags for case-insensitive matching. To set more than one flag, use an array.

@Pattern(regexp = "[a-z]+", flags = Pattern.Flag.CASE_INSENSITIVE)
String code;

@Pattern(regexp = "[a-z]+",
        flags = {Pattern.Flag.CASE_INSENSITIVE, Pattern.Flag.UNICODE_CASE})
String code2;

// インラインフラグでも同じことができる。一部だけに効かせるなら (?i:...) の形
@Pattern(regexp = "ABC-(?i:[a-z]+)")
String code3;

These are the most commonly used flags:

FlagMeaning
CASE_INSENSITIVEIgnores case (on its own, applies to ASCII only)
UNICODE_CASEExtends case-insensitive matching to non-ASCII letters such as full-width characters (only works together with CASE_INSENSITIVE)
COMMENTSIgnores whitespace and anything after # in the pattern
DOTALLMakes . match line terminators too

Pattern.Flag has no equivalent of UNICODE_CHARACTER_CLASS. If you need it, write (?U) inline.

Setting Error Messages with the message Attribute

The default message embeds {regexp}, so users see the raw regular expression. If the message is returned to a UI or in an API response, you should set message.

An attribute name in curly braces, such as {regexp}, is replaced with that attribute’s value. If you write a key instead, the text is looked up in ValidationMessages.properties at the root of the classpath.

@Pattern(regexp = Regexps.PHONE, message = "{user.phone.pattern}")
String phone;
# src/main/resources/ValidationMessages.properties
user.phone.pattern=電話番号はハイフンなしの半角数字10〜11桁で入力してください
# 開発者向けのメッセージなら属性値の埋め込みも便利
debug.pattern=値が {regexp} に一致しません

Since Java 9, properties resource bundles are read as UTF-8, so you can write non-ASCII text such as Japanese directly.

In Spring Boot 3.x, keys are also resolved from the application’s messages.properties (MessageSource), and if the same key exists in both, MessageSource takes precedence. Keeping messages in just one of the two files avoids confusion. To return errors as JSON in a consistent format, see How to Return Unified Error Responses with @RestControllerAdvice.

Practical Regex Patterns

The patterns below can be copied as-is. They are collected in a constants class. For email addresses, use @Email instead of writing your own regex.

public final class Regexps {
    // 電話番号(ハイフンなし)
    public static final String PHONE = "0\\d{9,10}";
    // 電話番号(ハイフンあり)
    public static final String PHONE_HYPHEN = "0\\d{1,4}-\\d{1,4}-\\d{4}";
    // 郵便番号(ハイフン任意)
    public static final String ZIP_CODE = "\\d{3}-?\\d{4}";
    // 半角英数字のみ
    public static final String ALNUM = "[a-zA-Z0-9]+";
    // 全角カタカナ(長音記号・中黒を含む)
    public static final String KATAKANA = "[\\u30A0-\\u30FF]+";
    // 英大文字・英小文字・数字・記号を各1文字以上。使える文字は ASCII の印字可能文字だけ
    public static final String PASSWORD =
            "(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[!-/:-@\\[-`{-~])[!-~]*";

    private Regexps() {}
}
PatternAcceptedRejected
PHONE0312345678, 09012345678090-1234-5678, 9012345678
PHONE_HYPHEN03-1234-5678, 090-1234-567809012345678, 03-1234-567
ZIP_CODE123-4567, 1234567123-456, 123-4567
ALNUMabc123abc_123, abc
KATAKANAスズキ, ジョン・スミスすずき, スズキ
PASSWORDPassw0rd!password1, Passw0rd

To accept phone numbers both with and without hyphens, you can combine the two as PHONE + "|" + PHONE_HYPHEN. Personally, though, I think it’s easier in the long run to strip hyphens before saving and validate only the hyphen-free format. PHONE_HYPHEN doesn’t check the number of digits in the area code, so values like “01-2-3456” also pass. If you need that level of strictness, use a custom constraint or a dedicated library.

The katakana range \u30A0-\u30FF includes the prolonged sound mark “ー” and the middle dot ”・”. Half-width katakana (\uFF65-\uFF9F) is not included, so decide in your spec whether to accept it.

In the password pattern, (?=.*[A-Z]) is a lookahead. It only checks that an uppercase letter appears somewhere, without consuming any characters. One lookahead is added for each character type, and the final [!-~]* limits which characters are allowed. Leave length checks to @Size rather than putting them in the regex. If you want a separate message for each rule, you can apply @Pattern more than once:

@NotBlank
@Size(min = 8, max = 64)
@Pattern(regexp = ".*[A-Z].*", message = "英大文字を1文字以上含めてください")
@Pattern(regexp = ".*\\d.*", message = "数字を1文字以上含めてください")
String password;

Testing Valid and Invalid Values Together with @ParameterizedTest

A regular expression doesn’t always behave the way its author thinks it does. Calling Validator directly, without a Spring context, keeps the tests fast.

import static org.assertj.core.api.Assertions.assertThat;

import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.constraints.Pattern;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

class PhonePatternTest {

    record Form(@Pattern(regexp = "^$|" + Regexps.PHONE) String phone) {}

    private static Validator validator;

    @BeforeAll
    static void setUp() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @ParameterizedTest
    @ValueSource(strings = {"0312345678", "09012345678", ""})
    void 通る値(String phone) {
        assertThat(validator.validateProperty(new Form(phone), "phone")).isEmpty();
    }

    @ParameterizedTest
    @CsvSource({
            "090-1234-5678, ハイフンあり",
            "9012345678, 先頭が0でない",
            "012345678, 桁不足",
            "09012345678, 全角数字"
    })
    void 弾かれる値(String phone, String reason) {
        assertThat(validator.validateProperty(new Form(phone), "phone"))
                .as(reason).isNotEmpty();
    }

    @Test
    void nullは通る() {
        assertThat(validator.validateProperty(new Form(null), "phone")).isEmpty();
    }
}

With spring-boot-starter-validation on the classpath, Hibernate Validator and the EL implementation are also available to tests, so this runs as-is. validateProperty validates only the field you name. Including the null and empty-string cases lets you confirm the behavior described in this article directly. For more on @CsvSource, see JUnit 5 Basics and @ParameterizedTest.

Common Pitfalls with Japanese Input

By default, Java’s \d matches only ASCII 0-9. As the test above shows, full-width digits are rejected. Adding (?U) makes \d match full-width digits as well.

Characters that look alike are another common problem. If the input contains a full-width hyphen ”-”, a minus sign ”−”, or a prolonged sound mark “ー”, it fails a pattern that expects a hyphen.

If you want to accept full-width input, an easy fix is to normalize the value with Normalizer.normalize(value, Normalizer.Form.NFKC) before validating it. Full-width digits and full-width hyphens become half-width, but the prolonged sound mark and the minus sign are not converted, so you need to replace those separately.

Avoiding Catastrophic Backtracking (ReDoS)

@Pattern runs the regular expression directly on request values. With some patterns, a crafted input can tie up the CPU.

// 危険:繰り返しの中の選択肢どうしが同じ文字にマッチする
// "aaaa...a!" のような入力でバックトラックが爆発し得る
"(a|aa)+"
"(\\w|\\d)+"

// 安全:選択肢が重ならないように書き直す
"a+"
"\\w+"

Since JDK 9, typical nested patterns like (a+)+ are optimized and may finish quickly. Patterns with overlapping alternatives or complex nesting can still be dangerous, though. As a rule, don’t nest quantifiers and don’t let alternatives overlap.

Be careful with @Size. Adding @Size alone doesn’t stop @Pattern from running. All constraints in the Default group are evaluated, so the regex still runs on input that is too long. If you want the length check to run first, fix the order as described in How to Control Validation Order with @GroupSequence, or limit the request size itself. For group basics, see How to Implement Group Validation with @Validated.

@Pattern or a Custom Constraint?

A simple rule of thumb:

  • For format-only checks on a single field, use @Pattern.
  • For checks that need logic, such as cross-field validation, database lookups, or check-digit calculation, use a custom constraint.
  • If you keep repeating the same @Pattern and message combination, it’s time to wrap it in its own annotation.

The third case doesn’t require a ConstraintValidator. You can just combine existing constraints. This is called a composed constraint.

@NotBlank
@Pattern(regexp = Regexps.PHONE)
@ReportAsSingleViolation
@Constraint(validatedBy = {})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface PhoneNumber {
    String message() default "{user.phone.pattern}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

With @ReportAsSingleViolation, any violation of the inner constraints is reported as a single message, the one from @PhoneNumber. This also fixes the “two error messages” problem described earlier. For full custom constraints that include logic, see How to Create a Custom Validation Annotation.

Summary

  • regexp must match the whole string because it uses matches(), so ^ and $ are unnecessary. For a partial match, surround the pattern with .*.
  • Patterns are Java strings, so escape them like \\d. Keeping patterns in constants is convenient.
  • null passes by specification, so add @NotBlank to required fields. For optional fields that should also accept empty strings, use the ^$|... form.
  • Use flags or (?i) to adjust matching, and message with ValidationMessages.properties to set the error text.
  • Leave length to @Size and limit the regex to format checks. If you want to check length first to guard against ReDoS, you need to fix the validation order.

Listing the values that should pass and the values that should be rejected in tests makes regular expressions much safer. Start by checking one of your own patterns with @ParameterizedTest.