Hartimer
Hartimer

Reputation: 545

How to allow javax.validation to be ignored in some cases

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

Upvotes: 3

Views: 7893

Answers (2)

Ishfaq
Ishfaq

Reputation: 430

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());
}

Upvotes: 1

Aravind Yarram
Aravind Yarram

Reputation: 80176

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

Upvotes: 10

Related Questions