3

Given the following class

public class Website {

    @NotNull
    String owner:

    @ValidUrl
    String url;

}

When we validate that (e.g. using @Valid) and if Website.url does not respect my custom @ValidUrl constraint we'll get an constraint violation (e.g. "url is unreachable").

I was wondering if it is possible to ignore that validation if the user wants to.

Steps:

  1. Validate form for the 1st time
  2. Throw constraint violation and show it to the user
  3. User chooses "I know, add it anyway" and re-submit
  4. Validate form for the 2nd time, validating everything except @ValidUrl
Hartimer
  • 525
  • 6
  • 20

2 Answers2

10

You can do this by a combination of using validation groups and programmatic validation.

Community
  • 1
  • 1
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
1

Here is a way you can remove a violation from a set of violation.

public static <T> Set<ConstraintViolation<T>> removeViolation(final Set<ConstraintViolation<T>> constraintViolations, final String propertyName, final Class annotationClass) {
    return constraintViolations.stream().filter(p ->
            !(((NodeImpl) (((PathImpl) (p.getPropertyPath())).getLeafNode())).getName().equals(propertyName))
                    || !((ConstraintDescriptorImpl) p.getConstraintDescriptor()).getAnnotationType().getSimpleName().equals(annotationClass.getSimpleName()))
            .collect(Collectors.toSet());
}
Ishfaq
  • 402
  • 4
  • 8