Skip to content

Instantly share code, notes, and snippets.



Last active Dec 17, 2015
What would you like to do?
Clojure Data Validator in 10 lines
(defn validate [data schema]
(into {} (for [[x y] schema]
[x (if (contains? data x)
(let [res (x data)]
(try (y res) (catch IllegalArgumentException e false)))
(defn valid? [data schema]
(every? true? (vals (validate data schema))))

Clojure Data Validator in 10 lines


Just for fn.


Define schema

(def schema {:age integer?
             :gender #(boolean (some (partial = %) ["m" "w"]))})

Extract general validation functions

(defn in? [xs]
  #(boolean (some (partial = %) xs)))

(def schema {:age integer?
             :gender (in? ["m" "w"])})

Validate data

(valid? {:name "John" :age 20 :gender "m"} schema) ; => true
(valid? {:name "John" :gender "m"} schema) ; => false
(validate {:name "John" :gender "m"} schema) ; => {:age false, :gender true}

Known limitations :)

  • One validation function per field
  • No error messages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment