0Pricing
Spring Boot 4 Microservices & REST APIs · Lekcja

Własne walidatory

Pisz własne ograniczenia walidacji

Własne walidatory to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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

Często zadawane pytania

Czy lekcja „Własne walidatory” jest bezpłatna?

Tak — pełny tekst „Własne walidatory” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „Własne walidatory”?

Pisz własne ograniczenia walidacji Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Własne walidatory”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Walidacja beanów za pomocą @Valid
  2. Własne walidatory
  3. @ControllerAdvice i @ExceptionHandler
  4. Szczegóły problemu (RFC 7807)
← Powrót do Spring Boot 4 Microservices & REST APIs