In my Spring Boot application I have a following method:
Decision create(@NotBlank String name, String url, @NotNull User author);
Right now directly in the code I'm checking a following condition:
if (!org.apache.commons.lang3.StringUtils.isEmpty(url) && !urlValidator.isValid(url)) {
throw new IllegalArgumentException("Decision url is not valid");
}
In other word - url
parameter can be null
or a valid url.
Is it possible to replace this code with an existing validation annotation(for example JSR-303) ?
Bean Validation spec does not contain a constraint for url but some of implementors add that constraints as a extension like @URL of Hibernate Validator but remember usage of extensions damage portability, to avoid that you can create your own validator based on regex. For other part you can use @NotBlank for url string empty control which you used for name string it looks like you have confusion between @NotNull, @NotBlank, NotEmpty constraints.
Take a look at this answer for that : https://stackoverflow.com/a/17137308/5964741
But no matter if you choose extensions or create your own validator Empty control for url string will be redundant.