Skip to content

Instantly share code, notes, and snippets.

@pleasetrythisathome
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pleasetrythisathome/e73955901343eb56fbdd to your computer and use it in GitHub Desktop.
Save pleasetrythisathome/e73955901343eb56fbdd to your computer and use it in GitHub Desktop.
clj validators
(defn validator
[msg fn]
(letfn [(validate [& args]
(apply fn args))]
(with-meta validate {:msg msg})))
(defn checker
[& validators]
(fn [v]
(clojure.core/reduce (fn [errors validator]
(if (validator v)
errors
(conj errors (:msg (meta validator))))) [] validators)))
;; example
(def validate (checker (validator "must not be zero" #(not (zero? %)))))
(validate 1) ;; -> []
(validate 0) ;; -> ["must not be zero"]
(def validate (checker (validator "must be positive" pos?)
(validator "must be an integer" integer?)
(validator "must be > 5" #(< 5 %))))
(validate -1) ;; -> ["must be positive" "must be > 5"]
(validate 4.0) ;; -> ["must be an integer" "must be > 5"]
(validate 6) ;; -> []
(if (seq? (validate value))
(do-invalid)
(do-valid))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment