Skip to content
AlexBaranosky edited this page Dec 30, 2012 · 6 revisions

Let's say you have an example map holding the data for a user in your system:

(def user {:name {:first "Alex"
                  :middle "Nicholas"
                  :last "Baranosky"}
           :date-of-birth #inst "1980-02-06T17:00:32.312000000-00:00"
           :siblings [user2 user3]})

You can quickly generate a basic schema with the Anything simple-schema for each path in the nested map. Anything will always pass, provided that the path is present in the map.

In the REPL run:

(use 'clj-schema.schema)

(scaffold-schema 'user-schema user)
;; => (def-map-schema user-schema [[:date-of-birth] Anything [:siblings] Anything [:name :first] Anything [:name :last] Anything [:name :middle] Anything])

;; which we can reformat like so
(def-map-schema user-schema
  [[:date-of-birth] Anything
   [:siblings] Anything]
   [:name :first] Anything
   [:name :last] Anything
   [:name :middle] Anything)  

Then adjust your schema to be more to your liking:

(use clj-schema.simple-schemas)
(import java.sql.Timestamp)

(def-map-schema user-schema
  [[:date-of-birth] Timestamp
   [:name :first] NonEmptyString
   [:name :last] NonEmptyString
   (optional-path [:name :middle]) NonEmptyString
   [:siblings] (sequence-of user-schema)])  

You can then check your original map user against the user-schema for validation errors like this:

(use 'clj-schema.validation)

(validation-errors user-schema user)
;; => #{}

(validation-errors user-schema (assoc user :car-type :jaguar))
;; => #{"Path [:car-type] was not specified in the schema."}
Clone this wiki locally