Bob Kuhar
Bob Kuhar

Reputation: 11140

How to verify if a String is a valid URL in Clojure

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?

Upvotes: 2

Views: 1506

Answers (1)

Sam Estep
Sam Estep

Reputation: 13354

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

Upvotes: 7

Related Questions