Clojure Schema validation

Schema is a Clojure library for declarative data description and validation. Basically it will throw exception when data is not what it is supposed to be.

Couldn’t find by googling a way to enable date to be either existing or not known (null). So when I figured it out, I wanted to share solution with everybody. The example requires that the person has a name (String), but birthdate (Date) is not required.

1
2
3
4
5
6
7
8
9
(:require [schema.core :as s])
 
(defn person
  [name born]
  (s/validate s/Str name)
  (s/validate (s/either java.util.Date (s/pred nil?)) born)
  {:name name
   :born born
  })

Oh, and it is also possible to combine different types like Integers and Strings for enum validation:

1
2
3
4
5
6
7
8
9
(:require [schema.core :as s])
 
(defn person
  [name hands]
  (s/validate s/Str name)
  (s/validate (s/enum 1 2 "none") hands)
  {:name name
   :hands hands
  })