0

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?

aardbol
  • 2,147
  • 3
  • 31
  • 42
  • Why not just use a group instead? https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html, https://beanvalidation.org/2.0/spec/#validationapi-validatorapi-groups – JB Nizet Dec 01 '18 at 16:54
  • I'm afraid I don't understand what you're suggesting – aardbol Dec 01 '18 at 19:59
  • If I understand correctly, you want to validate the EmailUnique constraint on create, but not on update. That's what validation groups are for. I linked to the Validated Spring annotation that allows specifying which group to apply, and the the bean validation specification explaining how to define validation groups. – JB Nizet Dec 01 '18 at 20:21

0 Answers0