0Pricing
Spring Boot 4 Microservices & REST APIs · บทเรียน

ตัวตรวจสอบแบบกำหนดเอง

เขียนข้อจำกัดการตรวจสอบของคุณเอง

ตัวตรวจสอบแบบกำหนดเอง เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 @Constraint annotation plus a ConstraintValidator
  • Override isValid; treat null as 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

คำถามที่พบบ่อย

บทเรียน “ตัวตรวจสอบแบบกำหนดเอง” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ตัวตรวจสอบแบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ตัวตรวจสอบแบบกำหนดเอง”

เขียนข้อจำกัดการตรวจสอบของคุณเอง คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “ตัวตรวจสอบแบบกำหนดเอง” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตรวจสอบบีนด้วย @Valid
  2. ตัวตรวจสอบแบบกำหนดเอง
  3. @ControllerAdvice และ @ExceptionHandler
  4. รายละเอียดปัญหา (RFC 7807)
← กลับไปที่ Spring Boot 4 Microservices & REST APIs