5

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) ?

alexanoid
  • 24,051
  • 54
  • 210
  • 410
  • 1
    Just use [`org.hibernate.validator.constraints.URL`](https://docs.jboss.org/hibernate/validator/5.2/api/org/hibernate/validator/constraints/URL.html) annotation. Portability isn't that big of a deal – Ali Dehghani Feb 04 '17 at 09:44

1 Answers1

3

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.

Community
  • 1
  • 1