Skip to content

Instantly share code, notes, and snippets.

@edtsech

edtsech/vali.clj

Last active Dec 17, 2015
Embed
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)))
false)])))
(defn valid? [data schema]
(every? true? (vals (validate data schema))))

Clojure Data Validator in 10 lines

Goal

Just for fn.

Usage

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