Video in progress
How do you write your own validator when the standard annotations aren't enough, and what are validation groups for?
You write an annotation and a ConstraintValidator for it. Groups let you validate the same DTO with different rules in different situations (create vs. update).
📖 Answer
A validator for an Uzbek phone number:
@Target({FIELD, PARAMETER}) @Retention(RUNTIME)
@Constraint(validatedBy = UzPhoneValidator.class)
public @interface UzPhone {
String message() default "Telefon raqami +998XXXXXXXXX ko'rinishida bo'lsin";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class UzPhoneValidator implements ConstraintValidator<UzPhone, String> {
private static final Pattern P = Pattern.compile("\\+998(33|50|7\\d|8\\d|9\\d)\\d{7}");
public boolean isValid(String v, ConstraintValidatorContext c) {
return v == null || P.matcher(v).matches(); // @NotNull checks null
}
}
If you need to validate several fields together (for example from < to), put the annotation on the class.
Groups work like this:
public interface OnCreate {}
public record ProductForm(
@Null(groups = OnCreate.class) Long id,
@NotBlank String name) {}
@PostMapping
ProductDto create(@Validated(OnCreate.class) @RequestBody ProductForm f) { ... }
When groups multiply, nobody can tell which rule applies when. Often it's simpler to write separate DTOs for create and update.
Don't go to the database from inside a validator (a "is the email taken" check). That's a business rule, and it belongs in the service.
Sign up to mark studied questions and save your progress.