2

I was wondering if Clojure has any facility better than the ones described on How to verify if a String in Java is a valid URL for detecting if a given String is a valid URL.

Is there anyone wrapping Apache Commons Validator? Is there a stand-alone library out there of which I am unaware?

Community
  • 1
  • 1
Bob Kuhar
  • 10,838
  • 11
  • 62
  • 115
  • Possible duplicate of [Clojure Regex: If string is a URL, return string](https://stackoverflow.com/questions/28269117/clojure-regex-if-string-is-a-url-return-string) – Brad Koch Nov 29 '17 at 17:53

1 Answers1

7

If Apache Commons Validator does what you want, you can use it directly from Clojure. Add it to your dependencies:

[commons-validator "1.5.1"]

Then you can use the library basically the same way you would use it from Java by leveraging Clojure's Java interop features.

As an example, here's a direct translation of the answer by Esteban Cacavelos to the question you linked:

;;...your imports

(import (org.apache.commons.validator.routines UrlValidator))

(defn -main [& args]

  ;; Get an UrlValidator
  (let [default-validator (UrlValidator.)]
    (if (.isValid default-validator "http://www.apache.org")
      (println "valid"))
    (if (not (.isValid default-validator "http//www.oops.com"))
      (println "INvalid")))

  ;; Get an UrlValidator with custom schemes
  (let [custom-schemes (into-array ["sftp" "scp" "https"])
        custom-validator (UrlValidator. custom-schemes)]
    (if (not (.isValid custom-validator "http://www.apache.org"))
      (println "valid")))

  ;; Get an UrlValidator that allows double slashes in the path
  (let [double-slash-validator (UrlValidator. UrlValidator/ALLOW_2_SLASHES)]
    (if (.isValid double-slash-validator "http://www.apache.org//projects")
      (println "INvalid"))))
Sam Estep
  • 12,974
  • 2
  • 37
  • 75