Liking cljdoc? Tell your friends :D

Introduction to rules

Rule

What is a rule?

Rule is data. A map with keys and values which defines a field.

Allowed keys

  • Required keys for a rule
ParamTypeDescription
:keykeywordReference for the field to be checked
:type<allowed-types>Defines the type to this field
  • Optional keys
ParamTypeDescription
:reqbooleanIf the field is required or not
:req-dependscollectionA collection of other fields that
:req-fnfunctionCustom function to define if required
:namestringCustom name to the field
:minnumberMinimum value for a number
:maxnumberMax value for a number
:lengthintegerA fixed length for a string
:min-lengthintegerMinimum length of a string
:max-lengthintegerMax length of a string
:containsvector or setSet of values allowed to the field
:formatregexA regex to validate value format
:format-fnfunctionCustom function to validate the value

Explaining some keys

Required fields

  • :req is trivial.
  • :req-depends: create dependencies between fields.

Example, Required field :document-type only when :document exists

(def my-rules
  [{:key :document :type String :req false}
   {:key :document-type :type String :req-depends [:document]}])
  • :req-fn: If you need a custom validation, this field allows you to create a function which receives the data as param and return a boolean.

Example: Required field :driver-license only if :age is >= 21

(defn custom-validator [data]
  (>= (:age data) 21))

(def my-rules2
  [{:key :age :type Integer :req false}
   {:key :driver-license :type String :req-fn custom-validator}])

Examples

(def my-rules3
 [{:key :first-name :type String :required true :min-length 1 :max-length 256}
  {:key :last-name :type String :required true :min-length 1 :max-length 256}
  {:key :date-of-birth :type String :required true :length 10}
  {:key :other-date-of-birth :type String :format #"\d{4}-\d{2}-\d{2}"}
  {:key :protocol-number :type Integer :required true}
  {:key :weight :type Double :min 0.001}
  {:key :classification :type String :contains ["A" "B" "C"]}])

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close