カスタムバリデーター
独自のバリデーション制約を書きます
「カスタムバリデーター」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Microservices & REST APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
When Built-ins Are Not Enough
Standard constraints cannot express every rule — a valid coupon code format, a phone number for a region, or a value that must exist in the database. For these you write a custom constraint backed by a validator.
Two Parts of a Custom Constraint
A custom constraint has two pieces:
- An annotation that you place on fields or parameters
- A ConstraintValidator that contains the actual checking logic
Defining the Annotation
Create the annotation and link it to its validator with @Constraint. Declare the standard message, groups, and payload members required by the spec.
@Target({ FIELD, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = StrongPasswordValidator.class)
public @interface StrongPassword {
String message() default "Password is not strong enough";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Implementing ConstraintValidator
The validator implements ConstraintValidator<Annotation, Type> and overrides isValid. Return true when the value satisfies the rule.
public class StrongPasswordValidator
implements ConstraintValidator<StrongPassword, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
if (value == null) return true; // let @NotNull handle null
return value.length() >= 8
&& value.chars().anyMatch(Character::isDigit)
&& value.chars().anyMatch(Character::isUpperCase);
}
}Null-Handling Convention
By convention a custom validator treats null as valid, delegating null-checking to @NotNull. This keeps constraints composable — each rule does one job.
Using the Custom Constraint
Apply your annotation just like a built-in one. Combined with @Valid on the controller, it participates in the normal validation flow.
public class CreateUserRequest {
@NotBlank
@StrongPassword
private String password;
}Custom Violation Messages
Inside isValid you can disable the default message and add a contextual one, useful when a single annotation enforces several sub-rules.
ctx.disableDefaultConstraintViolation();
ctx.buildConstraintViolationWithTemplate(
"Password must include a digit and an uppercase letter")
.addConstraintViolation();
return false;Injecting Beans into a Validator
A ConstraintValidator is a Spring bean, so it can use constructor injection — enabling rules that consult a repository or service, such as uniqueness checks.
public class UniqueEmailValidator
implements ConstraintValidator<UniqueEmail, String> {
private final UserRepository repo;
public UniqueEmailValidator(UserRepository repo) { this.repo = repo; }
@Override
public boolean isValid(String email, ConstraintValidatorContext ctx) {
return email == null || !repo.existsByEmail(email);
}
}Class-Level Constraints
Some rules span multiple fields — "password must equal confirmPassword." Target the annotation at TYPE and validate the whole object, accessing several fields together.
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordsMatchValidator.class)
public @interface PasswordsMatch {
String message() default "Passwords do not match";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Initialization Hook
Override initialize to capture attributes from the annotation instance, such as a configurable minimum length, before validation runs.
@Override
public void initialize(StrongPassword ann) {
this.minLength = ann.minLength();
}Keep Validators Pure and Fast
Validators run on every request, so keep them quick and side-effect-free where possible. Database-backed checks are fine but should be indexed and lightweight to avoid slowing request handling.
Quick Check
Test your understanding of custom validators.
Recap
Custom validators extend Bean Validation.
- A constraint is an
@Constraintannotation plus aConstraintValidator - Override
isValid; treatnullas valid by convention - Validators are beans, so they support constructor injection
- Use class-level constraints for cross-field rules
- Customize messages via the validation context
よくある質問
「カスタムバリデーター」レッスンは無料ですか?
はい。「カスタムバリデーター」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。
「カスタムバリデーター」で何を学びますか?
独自のバリデーション制約を書きます ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Spring Boot 4 Microservices & REST APIsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSpring Boot 4 Microservices & REST APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「カスタムバリデーター」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSpring Boot 4 Microservices & REST APIsレッスンでコードを書いて実行できますか?
はい。すべてのSpring Boot 4 Microservices & REST APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。