Reputation: 545
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:
Upvotes: 3
Views: 7893
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
Reputation: 80176
You can do this by a combination of using validation groups and programmatic validation.
Upvotes: 10