การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง
สร้างตัวตรวจสอบที่กำหนดเองและนำกลับมาใช้ซ้ำได้ด้วย ConstraintValidator สำหรับตรรกะการตรวจสอบเฉพาะโดเมน
การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Custom Constraints?
Bean Validation ships with annotations like @NotNull, @Size, and @Email. But real applications have domain-specific rules that no built-in annotation covers.
- A username must be lowercase and 3-20 chars
- A phone number must match your country's format
- A status field must be one of an allowed enum set
Instead of writing manual checks in every controller or service, you can build a reusable custom constraint annotation that plugs into the same validation pipeline as the built-in ones.
The Two Pieces of a Custom Constraint
Every custom constraint in Spring Boot 4 (which uses Jakarta Bean Validation) has exactly two parts:
- The annotation — what you write on a field, e.g.
@ValidUsername. It declares metadata and points to a validator. - The ConstraintValidator — a class containing the actual
isValid()logic.
The @Constraint meta-annotation links the two together. When validation runs, the framework instantiates your validator and calls isValid() for each annotated field.
Defining the Annotation
A custom constraint annotation must declare three standard attributes: message, groups, and payload. The @Constraint(validatedBy = ...) wires it to a validator class.
Note the imports come from jakarta.validation, not the old javax.validation.
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = UsernameValidator.class)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidUsername {
String message() default "invalid username";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Understanding @Target and @Retention
Two meta-annotations control where and when your constraint applies:
- @Target — where the annotation can be placed.
FIELDfor entity fields,PARAMETERfor method args,METHODfor getters,TYPE_USEfor generics likeList<@ValidUsername String>. - @Retention(RUNTIME) — the annotation must survive into runtime so the validation engine can read it via reflection. This is mandatory;
SOURCEorCLASSretention would make the constraint invisible.
Writing the ConstraintValidator
The validator implements ConstraintValidator<A, T>, where A is your annotation type and T is the type of the value being validated (e.g. String).
The isValid() method returns true if valid. A key rule: treat null as valid and let @NotNull handle nullness separately. This keeps each constraint focused on one concern.
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UsernameValidator
implements ConstraintValidator<ValidUsername, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
if (value == null) {
return true; // let @NotNull handle null
}
return value.matches("^[a-z0-9_]{3,20}$");
}
}Applying the Constraint
Once defined, your constraint is used exactly like a built-in one. Place it on a DTO field and combine it with other constraints. Spring evaluates all of them when the object is validated.
Use @NotNull alongside @ValidUsername since the validator deliberately allows null.
import jakarta.validation.constraints.NotNull;
public record RegisterRequest(
@NotNull
@ValidUsername(message = "username must be 3-20 lowercase chars")
String username,
@NotNull
String password
) {}Triggering Validation in a Controller
To run validation on incoming request bodies, annotate the parameter with @Valid. If any constraint fails, Spring throws a MethodArgumentNotValidException before your method body runs.
The message you set on the annotation becomes the error message reported back to the client.
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping("/register")
public String register(@Valid @RequestBody RegisterRequest req) {
return "registered: " + req.username();
}
}Customizing the Error Message Dynamically
Sometimes a static message isn't enough — you want the message to reflect why validation failed. Use the ConstraintValidatorContext to disable the default message and build a custom one.
You must call disableDefaultConstraintViolation() first, then add your own violation, otherwise both messages appear.
@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
if (value == null) return true;
if (value.length() < 3 || value.length() > 20) {
ctx.disableDefaultConstraintViolation();
ctx.buildConstraintViolationWithTemplate(
"username length must be between 3 and 20")
.addConstraintViolation();
return false;
}
return value.matches("^[a-z0-9_]+$");
}Passing Parameters to Your Constraint
Make constraints configurable by adding attributes to the annotation. For example, a @ValidUsername that accepts min and max length.
The validator reads these in initialize(), which runs once before isValid() calls.
public @interface ValidUsername {
String message() default "invalid username";
int min() default 3;
int max() default 20;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}Reading Parameters in initialize()
Override initialize() to capture the annotation's attribute values into fields. The framework calls it once per validator instance, before any isValid() invocation.
This lets one validator class serve many different configurations.
public class UsernameValidator
implements ConstraintValidator<ValidUsername, String> {
private int min;
private int max;
@Override
public void initialize(ValidUsername ann) {
this.min = ann.min();
this.max = ann.max();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext ctx) {
if (value == null) return true;
return value.length() >= min && value.length() <= max
&& value.matches("^[a-z0-9_]+$");
}
}Pure-Java: The Validation Logic Standalone
The core regex and length logic is plain Java you can test without any framework. Here is the same rule expressed as a runnable program to prove the logic before wiring it into Spring.
This isolation makes your validators easy to unit test.
public class Main {
static boolean isValidUsername(String value, int min, int max) {
if (value == null) return true;
return value.length() >= min && value.length() <= max
&& value.matches("^[a-z0-9_]+$");
}
public static void main(String[] args) {
System.out.println(isValidUsername("alice_99", 3, 20)); // true
System.out.println(isValidUsername("Al", 3, 20)); // false
System.out.println(isValidUsername("Bad Name", 3, 20)); // false
System.out.println(isValidUsername(null, 3, 20)); // true
}
}Quick Check
You implement a custom ConstraintValidator for a String field. The field is optional, and a separate @NotNull already guards nullness. What should isValid() return when the value is null?
Recap
You learned how to build reusable custom constraint annotations in Spring Boot 4:
- A constraint has two parts: the annotation (with
message,groups,payload) and a ConstraintValidator. @Constraint(validatedBy = ...)links them;@Retention(RUNTIME)and@Targetcontrol visibility and placement.isValid()holds the logic and should treatnullas valid, deferring to@NotNull.- Use
initialize()to read annotation parameters, andConstraintValidatorContextto craft dynamic messages. - Apply the constraint on DTO fields and trigger it with
@Validin controllers.
With these patterns, domain rules live in one tested place and plug seamlessly into Spring's validation pipeline.
คำถามที่พบบ่อย
บทเรียน “การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง”
สร้างตัวตรวจสอบที่กำหนดเองและนำกลับมาใช้ซ้ำได้ด้วย ConstraintValidator สำหรับตรรกะการตรวจสอบเฉพาะโดเมน คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ข้อจำกัดการตรวจสอบ Bean และกลุ่มข้อจำกัด
- การสร้างคำอธิบายประกอบข้อจำกัดแบบกำหนดเอง
- การจัดการข้อยกเว้นทั่วโลกด้วย @ControllerAdvice
- การตอบกลับรายละเอียดปัญหา RFC 7807