Schemallic unifies schema.core contracts, malli machinery, and pydantic-like validations — plus much more.
Schemallic is a cross-ecosystem schema toolkit for Clojure: it keeps the schema.core
syntax you already know, adds pydantic-style inline constraints, and runs validation,
coercion and schema ops through malli. It generates random schemas and seeded data,
compares and combines schemas, and offers optional reitit integration.
A semantic bridge between schema.core and malli.
(require '[schemallic.core :as s] '[schemallic.malli :as m] '[schemallic.ops :as o] '[schemallic.gen :as g])
;; 1. Define reusable schemas (s/def User {:id s/Int :name s/Str :email s/Str}) (s/def CreateUserRequest {:name s/Str :email s/Str})
;; 2. Create validated variables (s/def current-user :- User {:id 1 :name "Alice" :email "alice@example.com"}) (s/def max-retries :- s/Int 3)
;; 3. Define validated functions (s/defn create-user :- User [req :- CreateUserRequest] {:id (rand-int 1000) :name (:name req) :email (:email req)})
Once schemas are defined here, the rest of the ecosystem operates on them:
schemallic.malli - Validate data and introspect schemas (m/validate User {:id 1 :name "Alice" :email "alice@example.com"}) ; => true (m/explain User {:id "bad"}) ; => error details (m/form User) ; => [:map {:closed true} [:id :int] ...]
schemallic.ops - Compare and combine schemas (o/equal User CreateUserRequest) ; => false (o/extend User {:age s/Int}) ; => [:map ...] (o/merge User {:id s/Str}) ; => [:map ...]
schemallic.gen - Generate random schemas and test data (g/gen-data User 42) ; => {:id -80, :name "hqobK52QK0tQYt02j3", :email "4RQbwt"} (g/gen-data User {:id 99} 42) ; => {:id 99, :name "hqobK52QK0tQYt02j3", :email "4RQbwt"} (g/gen-schema 3 2) ; => random schema map
schemallic.core - Schema wrappers, combinators, and macros (def, defn, =>)
Schema:
Schemallic:
Numeric:
Usage: ^{:min 0 :max 100} s/Int or {:age ^{:min 18} s/Int}
Schemallic unifies `schema.core` contracts, `malli` machinery, and `pydantic`-like validations — plus much more.
Schemallic is a cross-ecosystem schema toolkit for Clojure: it keeps the `schema.core`
syntax you already know, adds `pydantic`-style inline constraints, and runs validation,
coercion and schema ops through `malli`. It generates random schemas and seeded data,
compares and combines schemas, and offers optional `reitit` integration.
A semantic bridge between `schema.core` and `malli`.
## Quick Start
(require '[schemallic.core :as s]
'[schemallic.malli :as m]
'[schemallic.ops :as o]
'[schemallic.gen :as g])
;; 1. Define reusable schemas
(s/def User {:id s/Int :name s/Str :email s/Str})
(s/def CreateUserRequest {:name s/Str :email s/Str})
;; 2. Create validated variables
(s/def current-user :- User {:id 1 :name "Alice" :email "alice@example.com"})
(s/def max-retries :- s/Int 3)
;; 3. Define validated functions
(s/defn create-user :- User
[req :- CreateUserRequest]
{:id (rand-int 1000)
:name (:name req)
:email (:email req)})
Once schemas are defined here, the rest of the ecosystem operates on them:
schemallic.malli - Validate data and introspect schemas
(m/validate User {:id 1 :name "Alice" :email "alice@example.com"}) ; => true
(m/explain User {:id "bad"}) ; => error details
(m/form User) ; => [:map {:closed true} [:id :int] ...]
schemallic.ops - Compare and combine schemas
(o/equal User CreateUserRequest) ; => false
(o/extend User {:age s/Int}) ; => [:map ...]
(o/merge User {:id s/Str}) ; => [:map ...]
schemallic.gen - Generate random schemas and test data
(g/gen-data User 42) ; => {:id -80, :name "hqobK52QK0tQYt02j3", :email "4RQbwt"}
(g/gen-data User {:id 99} 42) ; => {:id 99, :name "hqobK52QK0tQYt02j3", :email "4RQbwt"}
(g/gen-schema 3 2) ; => random schema map
schemallic.core - Schema wrappers, combinators, and macros (def, defn, =>)
## Wrappers
Schema:
- Int, ; integer
- Str, ; string
- Num, ; number (int/float/ratio)
- Bool, ; true/false
- Any ; any value
- Keyword ; keyword
- Symbol ; symbol
- Inst ; java.util.Date / #inst
- Uuid ; java.util.UUID / #uuid
- pred ; arbitrary predicate
- eq ; exact value equality
- maybe ; nil or schema
- enum ; one of values
- cond-pre ; conditional on type
- constrained ; schema + post-condition
- conditional ; explicit pred/schema pairs
- either ; union (deprecated)
- both ; intersection (deprecated)
- recursive ; self-referential schema
- optional-key ; optional map key
- => ; function schema
## Macros
Schemallic:
- def ; define schema | validated var | regular var
- defn ; validated function (args, return, destructuring)
## Props
Numeric:
- :gt :lt :ge :le :min :max :multiple-of :positive :negative :even :odd
- :max-digits :min-digits :decimal-places :divisor-of :finite
String:
- :min-length :max-length :pattern :re :starts-with :ends-with :contains
- :not-contains :lower-case :upper-case :non-blank :blank :format
Collection:
- :min-count :max-count :non-empty :empty :distinct
- :unique-items :unique :sorted :sorted-desc :contains
Generic:
- :pred :fn
Usage: ^{:min 0 :max 100} s/Int or {:age ^{:min 18} s/Int}(=> & args)Defines a function schema. Produces a Malli [:-> ...] schema directly.
(s/=> s/Int s/Int s/Int) ; => [:-> :int :int :int] (s/=> s/Str s/Str) ; => [:-> :string :string]
(s/=> (=> s/Str s/Str) (=> s/Str s/Str s/Int)) ; => [:function [:-> :string :string] [:-> :string :int :string]]
(s/def AddFn (s/=> s/Int s/Int s/Int)) (s/def ParseFn (s/=> (=> s/Str s/Str) (=> s/Str s/Str s/Int)))
Args: In single-arity mode, first arg is return type, rest are arg types. In multi-arity mode, each arg is an (=> ReturnType ArgType ...) form.
Defines a function schema. Produces a Malli [:-> ...] schema directly.
## Single arity:
(s/=> s/Int s/Int s/Int) ; => [:-> :int :int :int]
(s/=> s/Str s/Str) ; => [:-> :string :string]
## Multi-arity:
(s/=> (=> s/Str s/Str)
(=> s/Str s/Str s/Int))
; => [:function [:-> :string :string] [:-> :string :int :string]]
## Used with s/def:
(s/def AddFn (s/=> s/Int s/Int s/Int))
(s/def ParseFn (s/=> (=> s/Str s/Str)
(=> s/Str s/Str s/Int)))
Args: In single-arity mode, first arg is return type, rest are arg types.
In multi-arity mode, each arg is an (=> ReturnType ArgType ...) form.Any value, including nil. Use as a wildcard or escape hatch.
(s/def Metadata {s/Keyword s/Any}) (m/validate Metadata {:foo 1 :bar "x" :baz nil}) ; => true
Any value, including nil. Use as a wildcard or escape hatch.
## Examples:
(s/def Metadata {s/Keyword s/Any})
(m/validate Metadata {:foo 1 :bar "x" :baz nil}) ; => trueBoolean true or false. Does not coerce truthy/falsy values.
(s/def IsActive s/Bool) (m/validate IsActive true) ; => true (m/validate IsActive false) ; => true (m/validate IsActive 1) ; => false (m/validate IsActive nil) ; => false
Boolean true or false. Does not coerce truthy/falsy values. ## Examples: (s/def IsActive s/Bool) (m/validate IsActive true) ; => true (m/validate IsActive false) ; => true (m/validate IsActive 1) ; => false (m/validate IsActive nil) ; => false
A value that must satisfy every schema in schemas.
Deprecated in schema.core, but fully supported by schemallic.
Prefer constrained for new code.
(s/def PosInt (s/both s/Int (s/pred pos?))) (m/validate PosInt 5) ; => true (m/validate PosInt -1) ; => false
A value that must satisfy every schema in schemas. Deprecated in schema.core, but fully supported by schemallic. Prefer `constrained` for new code. ## Examples: (s/def PosInt (s/both s/Int (s/pred pos?))) (m/validate PosInt 5) ; => true (m/validate PosInt -1) ; => false
Conditional schema with explicit predicate/schema pairs.
Converts each pair to [:and [:fn pred] schema] under [:or ...]; a value passes when any branch matches. No greedy first-match behavior.
(s/def NumOrStr (s/cond-pre integer? s/Int string? s/Str)) (m/validate NumOrStr 42) ; => true (m/validate NumOrStr "hi") ; => true
Conditional schema with explicit predicate/schema pairs. Converts each pair to [:and [:fn pred] schema] under [:or ...]; a value passes when any branch matches. No greedy first-match behavior. ## Examples: (s/def NumOrStr (s/cond-pre integer? s/Int string? s/Str)) (m/validate NumOrStr 42) ; => true (m/validate NumOrStr "hi") ; => true
Conditional schema with explicit predicates, like cond for schemas.
Takes pairs of (pred schema). Converts to [:or ...] of [:and [:fn pred] schema] branches. No match returns false unless :else exists.
(s/def IdOrName (s/conditional integer? s/Int string? s/Str)) (m/validate IdOrName 1) ; => true (m/validate IdOrName "bob") ; => true
(s/def Shape (s/conditional #(= :circle (:type %)) Circle #(= :rect (:type %)) Rect :else s/Any))
Conditional schema with explicit predicates, like cond for schemas.
Takes pairs of (pred schema). Converts to [:or ...] of
[:and [:fn pred] schema] branches. No match returns false unless :else exists.
## Examples:
(s/def IdOrName (s/conditional integer? s/Int string? s/Str))
(m/validate IdOrName 1) ; => true
(m/validate IdOrName "bob") ; => true
(s/def Shape (s/conditional #(= :circle (:type %)) Circle
#(= :rect (:type %)) Rect
:else s/Any))A schema with an additional post-condition predicate.
Validates the value against the base schema first, then runs the predicate. Produces better error messages than wrapping with pred alone, and works well with coercion since the predicate runs after coercion.
(s/def PositiveInt (s/constrained s/Int pos?)) (m/validate PositiveInt 5) ; => true (m/validate PositiveInt -1) ; => false
A schema with an additional post-condition predicate. Validates the value against the base schema first, then runs the predicate. Produces better error messages than wrapping with pred alone, and works well with coercion since the predicate runs after coercion. ## Examples: (s/def PositiveInt (s/constrained s/Int pos?)) (m/validate PositiveInt 5) ; => true (m/validate PositiveInt -1) ; => false
(def & args)Define a named schema OR a validated variable with schema.core type annotations.
;; Schema definitions (reusable types) (s/def User {:id s/Int :name s/Str :email s/Str}) (s/def Post {:author User :content s/Str :created s/Inst})
;; Validated variables (runtime validation) (s/def username :- s/Str "john") (s/def config :- {:port s/Int} {:port 3000})
;; Validated variable with metadata on the symbol (s/def ^{:doc {:summary "A username"}} username :- s/Str "john")
;; Validated variable with docstring (s/def username "The user's name" :- s/Str "john")
;; Validated variable with both docstring and metadata (s/def ^{:doc {:summary "A username"}} username "The user's name" :- s/Str "john")
;; Closed vs open schemas (via ^{} reader metadata on the map) (s/def StrictUser ^{:closed true} {:id s/Int :name s/Str}) ; no extra keys allowed (s/def FlexibleUser ^{:closed false} {:id s/Int :name s/Str}) ; extra keys allowed
;; Docstring + reader metadata (both on the schema) (s/def UserProfile "A validated user profile" ^{:author "team" :version "1.0"} {:id s/Int :name s/Str :email s/Str})
;; Docstring + with-meta (both on the schema) (s/def UserProfile "A validated user profile" (with-meta {:id s/Int :name s/Str :email s/Str} {:author "team" :version "1.0"}))
;; with-meta alone (no docstring) (s/def UserProfile (with-meta {:id s/Int :name s/Str :email s/Str} {:author "team" :version "1.0"}))
;; Entry-level metadata (via ^{} on individual schema values) (s/def User {:id s/Int :name s/Str :email ^{:required true :doc "Primary email"} s/Str})
;; Constraint props (validation + generation hints) (s/def User {:id s/Int :name ^{:min-length 1 :max-length 50} s/Str :age ^{:min 0 :max 150} s/Int :email ^{:pattern "^.@.$"} s/Str :tags ^{:distinct true :min-count 1} [s/Str]})
For schema definitions (name schema):
For validated variables (name :- schema value):
For plain (name value) — no :- — the macro emits a regular def with NO validation. If a validated variable seems to enforce nothing, check the arg shape: (s/def x 42) is a plain var, (s/def x :- s/Int 42) validates.
Schema definitions and validated variables handle metadata differently:
Schema definitions (name schema):
Validated variables (name :- schema value):
In short: schema metadata -> Malli properties, var metadata -> Clojure tooling. If you need both, use a schema definition with metadata on the schema value, then reference it in a validated variable.
Syntax: ; Define reusable schema (def name schema) (def name ^{:closed true} schema) (def name "docstring" schema) (def name "docstring" ^{:closed true} schema) (def name "docstring" (with-meta schema meta)) (def name (with-meta schema meta)) (def name ^{:doc "..."} schema)
; Define validated variable (metadata on the symbol, not the schema) (def name :- schema value) (def name :- schema "docstring" value) (def name "docstring" :- schema value) (def ^{:doc {:any :map}} name :- schema value) (def ^{:doc {:any :map}} name "docstring" :- schema value) (def (with-meta name {:doc "desc"}) :- schema value) (def (with-meta name {:doc {:summary "s"}}) "docstring" :- schema value)
Define a named schema OR a validated variable with `schema.core` type annotations.
## Examples:
;; Schema definitions (reusable types)
(s/def User {:id s/Int :name s/Str :email s/Str})
(s/def Post {:author User :content s/Str :created s/Inst})
;; Validated variables (runtime validation)
(s/def username :- s/Str "john")
(s/def config :- {:port s/Int} {:port 3000})
;; Validated variable with metadata on the symbol
(s/def ^{:doc {:summary "A username"}} username :- s/Str "john")
;; Validated variable with docstring
(s/def username "The user's name" :- s/Str "john")
;; Validated variable with both docstring and metadata
(s/def ^{:doc {:summary "A username"}} username "The user's name" :- s/Str "john")
;; Closed vs open schemas (via ^{} reader metadata on the map)
(s/def StrictUser ^{:closed true} {:id s/Int :name s/Str}) ; no extra keys allowed
(s/def FlexibleUser ^{:closed false} {:id s/Int :name s/Str}) ; extra keys allowed
;; Docstring + reader metadata (both on the schema)
(s/def UserProfile
"A validated user profile"
^{:author "team" :version "1.0"}
{:id s/Int :name s/Str :email s/Str})
;; Docstring + with-meta (both on the schema)
(s/def UserProfile
"A validated user profile"
(with-meta {:id s/Int :name s/Str :email s/Str}
{:author "team" :version "1.0"}))
;; with-meta alone (no docstring)
(s/def UserProfile
(with-meta {:id s/Int :name s/Str :email s/Str}
{:author "team" :version "1.0"}))
;; Entry-level metadata (via ^{} on individual schema values)
(s/def User {:id s/Int
:name s/Str
:email ^{:required true :doc "Primary email"} s/Str})
;; Constraint props (validation + generation hints)
(s/def User {:id s/Int
:name ^{:min-length 1 :max-length 50} s/Str
:age ^{:min 0 :max 150} s/Int
:email ^{:pattern "^.*@.*$"} s/Str
:tags ^{:distinct true :min-count 1} [s/Str]})
## Validation Behavior
For schema definitions (name schema):
- Registers schema for use in nested/recursive references
- Applies closed/open map semantics based on ^{} metadata on the schema map
- Entry-level ^{} metadata becomes Malli entry properties
For validated variables (name :- schema value):
- Initial value is validated against schema at definition time
- Failures throw ExceptionInfo with detailed Malli explanations
- Metadata (reader ^{} or with-meta) on the symbol is preserved on the var
- Docstrings are preserved on the var as :doc metadata
For plain (name value) — no :- — the macro emits a regular def with NO
validation. If a validated variable seems to enforce nothing, check the
arg shape: (s/def x 42) is a plain var, (s/def x :- s/Int 42) validates.
## Metadata Placement
Schema definitions and validated variables handle metadata differently:
Schema definitions (name schema):
- Metadata goes on the schema VALUE (the map/vector/set)
- Becomes Malli properties via apply-meta (e.g. ^{:closed true} -> [:map {:closed true} ...])
- ^{:doc "..."} is copied to var metadata; ^{:author "..."} and
^{:version "..."} are dropped
Validated variables (name :- schema value):
- Metadata goes on the SYMBOL (which becomes the var)
- Survives as Clojure var metadata (visible via (meta #'name), doc, etc.)
- Does NOT become Malli properties (the schema is separate from the var)
In short: schema metadata -> Malli properties, var metadata -> Clojure tooling.
If you need both, use a schema definition with metadata on the schema value,
then reference it in a validated variable.
Syntax:
; Define reusable schema
(def name schema)
(def name ^{:closed true} schema)
(def name "docstring" schema)
(def name "docstring" ^{:closed true} schema)
(def name "docstring" (with-meta schema meta))
(def name (with-meta schema meta))
(def name ^{:doc "..."} schema)
; Define validated variable (metadata on the symbol, not the schema)
(def name :- schema value)
(def name :- schema "docstring" value)
(def name "docstring" :- schema value)
(def ^{:doc {:any :map}} name :- schema value)
(def ^{:doc {:any :map}} name "docstring" :- schema value)
(def (with-meta name {:doc "desc"}) :- schema value)
(def (with-meta name {:doc {:summary "s"}}) "docstring" :- schema value)(defn fn-name & args)Define a function with schema.core type annotations using malli validation.
Like schema.core/defn, but always validates - no need for with-fn-validation.
Uses malli under the hood for faster validation and richer error messages.
;; Basic function with validation (s/defn add-numbers :- s/Num [x :- s/Num y :- s/Num] (+ x y))
;; Function with a complex return schema (s/defn create-user :- {:id s/Int :name s/Str :email s/Str} [name :- s/Str email :- s/Str] {:id (rand-int 1000) :name name :email email})
;; Multi-arity functions (all arities share same return schema) (s/defn greet :- s/Str ([name :- s/Str] (str "Hello " name)) ([first :- s/Str last :- s/Str] (str "Hello " first " " last)))
;; Map destructuring (s/defn greet-user :- s/Str [{:keys [name age]} :- {:name s/Str :age s/Int}] (str "Hello " name ", age " age))
;; Vector destructuring (s/defn sum-coords :- s/Int [[x y z] :- [s/Int s/Int s/Int]] (+ x y z))
;; Mixed: destructured + simple args (s/defn format-user :- s/Str [{:keys [id name]} :- {:id s/Int :name s/Str} prefix :- s/Str] (str prefix " #" id " " name))
;; Nested map destructuring (s/defn person-address :- s/Str [{:keys [name] {:keys [street city]} :address} :- {:name s/Str :address {:street s/Str :city s/Str}}] (str name " lives at " street ", " city))
;; Nested vector destructuring (s/defn sum-nested :- s/Int [[x [y z]] :- [s/Int [s/Int s/Int]]] (+ x y z))
;; Rest args with map destructuring (s/defn greet-with-opts :- s/Str [name :- s/Str & {:keys [greeting]} :- {:greeting s/Str}] (str (or greeting "Hello") ", " name))
;; Rest args with vector destructuring (s/defn sum-rest :- s/Int [x :- s/Int & [y z] :- [s/Int s/Int]] (+ x (or y 0) (or z 0)))
;; Rest args with mixed destructuring (s/defn log-event :- s/Str [event :- s/Keyword & {:keys [level msg] :as opts} :- {:level s/Str :msg s/Str}] (str (name event) " [" level "] " msg))
;; :or defaults (keys with defaults are marked {:optional true}) (s/defn greet :- s/Str [{:keys [name greeting] :or {greeting "Hello"}} :- {:name s/Str :greeting s/Str}] (str greeting ", " name))
;; :syms destructuring (s/defn get-user :- s/Str [{user-name 'name user-age 'age} :- {'name s/Str 'age s/Int}] (str user-name " is " user-age))
;; Constraint props on a named arg schema (validation + generation hints) (s/def UserInput {:name ^{:min-length 1 :max-length 50} s/Str :age ^{:min 0 :max 150} s/Int :tags ^{:distinct true} [s/Str]})
(s/defn create-user :- {:id s/Int :name s/Str :email s/Str :age s/Int :tags [s/Str]} [input :- UserInput] {:id (rand-int 1000) :name (:name input) :email "user@example.com" :age (:age input) :tags (:tags input)})
&): sequences converted to maps/vectors before validation, nil rest args skippedAttaches :malli/schema to the var (same as malli.dev/start! expects):
(:malli/schema (meta #'add-numbers)) ; => [:-> :number :number :number]
Syntax: ; Define reusable function (s/defn fn-name :- ReturnSchema [arg1 :- Arg1Schema arg2 :- Arg2Schema] (function-body))
(s/defn fn-name :- ReturnSchema "docstring" [arg1 :- Arg1Schema arg2 :- Arg2Schema] (function-body))
(s/defn ^{:doc {:any :map}} fn-name :- ReturnSchema [arg1 :- Arg1Schema arg2 :- Arg2Schema] (function-body))
(s/defn ^{:doc {:any :map}} fn-name :- ReturnSchema "docstring" [arg1 :- Arg1Schema arg2 :- Arg2Schema] (function-body))
Define a function with `schema.core` type annotations using `malli` validation.
Like schema.core/defn, but always validates - no need for with-fn-validation.
Uses `malli` under the hood for faster validation and richer error messages.
## Examples:
;; Basic function with validation
(s/defn add-numbers :- s/Num
[x :- s/Num y :- s/Num]
(+ x y))
;; Function with a complex return schema
(s/defn create-user :- {:id s/Int :name s/Str :email s/Str}
[name :- s/Str email :- s/Str]
{:id (rand-int 1000) :name name :email email})
;; Multi-arity functions (all arities share same return schema)
(s/defn greet :- s/Str
([name :- s/Str]
(str "Hello " name))
([first :- s/Str last :- s/Str]
(str "Hello " first " " last)))
;; Map destructuring
(s/defn greet-user :- s/Str
[{:keys [name age]} :- {:name s/Str :age s/Int}]
(str "Hello " name ", age " age))
;; Vector destructuring
(s/defn sum-coords :- s/Int
[[x y z] :- [s/Int s/Int s/Int]]
(+ x y z))
;; Mixed: destructured + simple args
(s/defn format-user :- s/Str
[{:keys [id name]} :- {:id s/Int :name s/Str}
prefix :- s/Str]
(str prefix " #" id " " name))
;; Nested map destructuring
(s/defn person-address :- s/Str
[{:keys [name] {:keys [street city]} :address} :- {:name s/Str :address {:street s/Str :city s/Str}}]
(str name " lives at " street ", " city))
;; Nested vector destructuring
(s/defn sum-nested :- s/Int
[[x [y z]] :- [s/Int [s/Int s/Int]]]
(+ x y z))
;; Rest args with map destructuring
(s/defn greet-with-opts :- s/Str
[name :- s/Str & {:keys [greeting]} :- {:greeting s/Str}]
(str (or greeting "Hello") ", " name))
;; Rest args with vector destructuring
(s/defn sum-rest :- s/Int
[x :- s/Int & [y z] :- [s/Int s/Int]]
(+ x (or y 0) (or z 0)))
;; Rest args with mixed destructuring
(s/defn log-event :- s/Str
[event :- s/Keyword & {:keys [level msg] :as opts} :- {:level s/Str :msg s/Str}]
(str (name event) " [" level "] " msg))
;; :or defaults (keys with defaults are marked {:optional true})
(s/defn greet :- s/Str
[{:keys [name greeting] :or {greeting "Hello"}} :- {:name s/Str :greeting s/Str}]
(str greeting ", " name))
;; :syms destructuring
(s/defn get-user :- s/Str
[{user-name 'name user-age 'age} :- {'name s/Str 'age s/Int}]
(str user-name " is " user-age))
;; Constraint props on a named arg schema (validation + generation hints)
(s/def UserInput
{:name ^{:min-length 1 :max-length 50} s/Str
:age ^{:min 0 :max 150} s/Int
:tags ^{:distinct true} [s/Str]})
(s/defn create-user :- {:id s/Int :name s/Str :email s/Str :age s/Int :tags [s/Str]}
[input :- UserInput]
{:id (rand-int 1000)
:name (:name input)
:email "user@example.com"
:age (:age input)
:tags (:tags input)})
## Validation Behavior
- Arguments validated on function entry
- Return value validated before exit
- Destructuring: map/vector/mixed args validated against their schema; nested forms validated recursively
- Rest args (`&`): sequences converted to maps/vectors before validation, nil rest args skipped
- Failures throw ExceptionInfo:
- 'Argument validation failed: <details>'
- 'Return value validation failed: <details>'
## Malli Metadata
Attaches :malli/schema to the var (same as malli.dev/start! expects):
(:malli/schema (meta #'add-numbers))
; => [:-> :number :number :number]
## Limitations
- Return schema must be on function name (not the arg vector)
- :or-derived optionality is processed recursively through nested destructuring
- No final attr-map support on multi-arity functions
Syntax:
; Define reusable function
(s/defn fn-name :- ReturnSchema
[arg1 :- Arg1Schema arg2 :- Arg2Schema]
(function-body))
(s/defn fn-name :- ReturnSchema
"docstring"
[arg1 :- Arg1Schema arg2 :- Arg2Schema]
(function-body))
(s/defn ^{:doc {:any :map}} fn-name :- ReturnSchema
[arg1 :- Arg1Schema arg2 :- Arg2Schema]
(function-body))
(s/defn ^{:doc {:any :map}} fn-name :- ReturnSchema
"docstring"
[arg1 :- Arg1Schema arg2 :- Arg2Schema]
(function-body))A value that must satisfy at least one schema in schemas.
Deprecated in schema.core, but fully supported by schemallic.
Prefer conditional or cond-pre for new code.
(s/def NumOrStr (s/either s/Int s/Str)) (m/validate NumOrStr 42) ; => true (m/validate NumOrStr "hi") ; => true
A value that must satisfy at least one schema in schemas. Deprecated in schema.core, but fully supported by schemallic. Prefer `conditional` or `cond-pre` for new code. ## Examples: (s/def NumOrStr (s/either s/Int s/Str)) (m/validate NumOrStr 42) ; => true (m/validate NumOrStr "hi") ; => true
A value that must be equal to one of the given options.
(s/def Role (s/enum :admin :user :guest)) (m/validate Role :admin) ; => true (m/validate Role :guest) ; => true (m/validate Role :owner) ; => false
(s/def Direction (s/enum "north" "south" "east" "west"))
A value that must be equal to one of the given options. ## Examples: (s/def Role (s/enum :admin :user :guest)) (m/validate Role :admin) ; => true (m/validate Role :guest) ; => true (m/validate Role :owner) ; => false (s/def Direction (s/enum "north" "south" "east" "west"))
A schema that only accepts a single specific value.
(s/def AdminRole (s/eq :admin)) (m/validate AdminRole :admin) ; => true (m/validate AdminRole :user) ; => false
(s/def Zero (s/eq 0)) (m/validate Zero 0) ; => true (m/validate Zero 1) ; => false
A schema that only accepts a single specific value. ## Examples: (s/def AdminRole (s/eq :admin)) (m/validate AdminRole :admin) ; => true (m/validate AdminRole :user) ; => false (s/def Zero (s/eq 0)) (m/validate Zero 0) ; => true (m/validate Zero 1) ; => false
A java.util.Date / #inst timestamp.
(s/def CreatedAt s/Inst) (m/validate CreatedAt #inst "2024-01-01") ; => true (m/validate CreatedAt "2024-01-01") ; => false
A java.util.Date / #inst timestamp. ## Examples: (s/def CreatedAt s/Inst) (m/validate CreatedAt #inst "2024-01-01") ; => true (m/validate CreatedAt "2024-01-01") ; => false
Any integral number (Long, Integer, BigInteger, etc.).
(s/def UserId s/Int) (m/validate UserId 42) ; => true (m/validate UserId 3.14) ; => false (m/validate UserId "42") ; => false
Any integral number (Long, Integer, BigInteger, etc.). ## Examples: (s/def UserId s/Int) (m/validate UserId 42) ; => true (m/validate UserId 3.14) ; => false (m/validate UserId "42") ; => false
A Clojure keyword.
(s/def Status s/Keyword) (m/validate Status :active) ; => true (m/validate Status "active") ; => false (m/validate Status :a/b) ; => true (namespaced keywords too)
A Clojure keyword. ## Examples: (s/def Status s/Keyword) (m/validate Status :active) ; => true (m/validate Status "active") ; => false (m/validate Status :a/b) ; => true (namespaced keywords too)
A value that must either be nil or satisfy the given schema.
(s/def OptionalName (s/maybe s/Str)) (m/validate OptionalName "Alice") ; => true (m/validate OptionalName nil) ; => true (m/validate OptionalName 42) ; => false
A value that must either be nil or satisfy the given schema. ## Examples: (s/def OptionalName (s/maybe s/Str)) (m/validate OptionalName "Alice") ; => true (m/validate OptionalName nil) ; => true (m/validate OptionalName 42) ; => false
Any number (Long, Double, BigDecimal, etc.).
(s/def Price s/Num) (m/validate Price 9.99) ; => true (m/validate Price 42) ; => true (m/validate Price "9") ; => false
Any number (Long, Double, BigDecimal, etc.). ## Examples: (s/def Price s/Num) (m/validate Price 9.99) ; => true (m/validate Price 42) ; => true (m/validate Price "9") ; => false
Marks a map key as optional. Absent keys are valid, present ones are validated.
(s/def User {:id s/Int :name s/Str (s/optional-key :age) s/Int}) (m/validate User {:id 1 :name "Alice"}) ; => true (m/validate User {:id 1 :name "Alice" :age 30}) ; => true
Marks a map key as optional. Absent keys are valid, present ones are validated.
## Examples:
(s/def User {:id s/Int :name s/Str (s/optional-key :age) s/Int})
(m/validate User {:id 1 :name "Alice"}) ; => true
(m/validate User {:id 1 :name "Alice" :age 30}) ; => trueSchema defined by an arbitrary predicate function.
(s/def PositiveInt (s/pred pos? 'pos?)) (m/validate PositiveInt 5) ; => true (m/validate PositiveInt -1) ; => false (m/validate PositiveInt 0) ; => false
Schema defined by an arbitrary predicate function. ## Examples: (s/def PositiveInt (s/pred pos? 'pos?)) (m/validate PositiveInt 5) ; => true (m/validate PositiveInt -1) ; => false (m/validate PositiveInt 0) ; => false
Support for (mutually) recursive schemas by passing a var that points to a schema, e.g. (s/recursive #'ExampleRecursiveSchema).
Converts to a self-contained Malli [:schema {:registry ...} key] form whose self-references resolve locally via [:ref key].
(declare Tree) (s/def Tree {:value s/Int :children [(s/recursive #'Tree)]}) (m/validate Tree {:value 1 :children [{:value 2 :children []}]}) ; => true
Support for (mutually) recursive schemas by passing a var that points to a
schema, e.g. (s/recursive #'ExampleRecursiveSchema).
Converts to a self-contained Malli [:schema {:registry ...} key] form whose
self-references resolve locally via [:ref key].
## Examples:
(declare Tree)
(s/def Tree {:value s/Int :children [(s/recursive #'Tree)]})
(m/validate Tree {:value 1 :children [{:value 2 :children []}]}) ; => trueA string value.
(s/def Username s/Str) (m/validate Username "alice") ; => true (m/validate Username 42) ; => false (m/validate Username nil) ; => false
A string value. ## Examples: (s/def Username s/Str) (m/validate Username "alice") ; => true (m/validate Username 42) ; => false (m/validate Username nil) ; => false
A Clojure symbol.
(s/def FnName s/Symbol) (m/validate FnName 'my-fn) ; => true (m/validate FnName :my-fn) ; => false
A Clojure symbol. ## Examples: (s/def FnName s/Symbol) (m/validate FnName 'my-fn) ; => true (m/validate FnName :my-fn) ; => false
A java.util.UUID / #uuid value.
(s/def TraceId s/Uuid) (m/validate TraceId #uuid "550e8400-e29b-41d4-a716-446655440000") ; => true (m/validate TraceId "550e8400-e29b-41d4-a716-446655440000") ; => false
A java.util.UUID / #uuid value. ## Examples: (s/def TraceId s/Uuid) (m/validate TraceId #uuid "550e8400-e29b-41d4-a716-446655440000") ; => true (m/validate TraceId "550e8400-e29b-41d4-a716-446655440000") ; => false
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |