You can have a custom validator defined with whatever logic you want.
Then you can create a custom annotation for the validator and use it in your DTO just like @NotNull
public class CustomValidator implements ConstraintValidator<MyObject, String> {
.
.
.
}
--
@Constraint(validatedBy = { CustomValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactInfo {
String message() default "Invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
refer to this link for example: https://www.baeldung.com/spring-dynamic-dto-validation