Last active
August 29, 2015 14:00
-
-
Save pleasetrythisathome/e73955901343eb56fbdd to your computer and use it in GitHub Desktop.
clj validators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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