In my API project, I have a custom ConstraintValidator to check whether e-mail addresses aren't already associated with another account.
Interface:
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = EmailUniqueConstraintValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EmailUnique {
String message() default "cannot already be associated with another account";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The validator:
import com.demo.demoapp.repo.UserRepository;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class EmailUniqueConstraintValidator implements ConstraintValidator<EmailUnique, String> {
private UserRepository userRepository;
public EmailUniqueConstraintValidator(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value == null || !userRepository.existsByEmail(value);
}
}
This validator is added to the user creation request object and will correctly check the existance of the e-mail address and give back an error to BindingResult if it's the case.
But when editing the user, things become more complicated. The user object has to be passed to the API entirely except for the object so this constraint validator would always be triggered. So I would like to remove the @EmailUnique annotation from the class and manually trigger it in the Service. Is that possible?