Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.2 kB
1
Indexable
Never
public class SelfValidator implements ConstraintValidator<SelfValidator.SelfValidation, SelfValidator.SelfValidate> {
  private static final String DEFAULT_MESSAGE = "error.self.validation.failed";

  @Inherited
  @Target(ElementType.TYPE)
  @Retention(RetentionPolicy.RUNTIME)
  @Constraint(validatedBy = SelfValidator.class)
  public @interface SelfValidation {
    String message() default DEFAULT_MESSAGE;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
  }

  public interface SelfValidate {
    boolean validate(final ConstraintValidatorContext ctx);
  }


  @Override
  public void initialize(final SelfValidation selfValidation) {
  }

  @Override
  public boolean isValid(final SelfValidate selfValidate, final ConstraintValidatorContext ctx) {
    boolean valid = selfValidate.validate(ctx);
    ctx.disableDefaultConstraintViolation();
    return valid;
  }

  public static void addViolation(final ConstraintValidatorContext ctx, final String field, final String message) {
    ctx.buildConstraintViolationWithTemplate(message)
      .addPropertyNode(field)
      .addConstraintViolation();
  }
}