Easy clojure form validations
Make your deps.edn
look like this:
coast-framework/validator {:mvn/version "2.0.1"}
Require it like this
(ns your-project
(:require [validator.core :as validator]))
First, define the table and columns to be validated
(def params
(validator/params :account
[:required [:email :password]]))
Then validate a ring request map
(let [account {:params {:account {:email "[email protected]" :password "correct battery horse staple"}}}]
(params account))
; returns
{:account {:email "[email protected]" :password "correct battery horse staple"}}
Qualified keyword maps work too!
(params {:params {:account/email "[email protected]"}})
; => returns {:account/email "[email protected]"}
When there's a validation error, an exception is thrown
(params {:params {:account/email ""}})
; => clojure.lang.ExceptionInfo {:ex-data :error.core/e {:email "Email must not be blank"}}
Custom messages are supported
(def params
(validator/params :account
[:required [:email :password] "is required"]))
(params {:params {}})
; => clojure.lang.ExceptionInfo {:ex-data :error.core/e {:email "Email is required" :password "Password is required"}}
Below is the list of available, built in validator rules
- :required [msg] - must not be absent, blank, or nil
- :contains [msg] - must not be absent, but can be blank or nil
- :not-blank [msg] - may be absent but not blank or nil
- :exact [msg] - must be a particular value
- :equal [msg] - all keys must be equal
- :email [msg] - must be a valid email
- :url [msg] - must be a valid URL
- :web-url [msg] - must be a valid website URL (http or https)
- :link-url [msg] - must be a valid link URL (can be relative, http: or https: may be omitted)
- :matches [msg] - must match a regular expression
- :min-length [msg] - must be a certain length (for strings or collections)
- :max-length [msg] - must not exceed a certain length (for strings or collections)
- :complete [msg] - must be a collection with no blank or nil values
- :min-val [msg] - must be at least a certain value
- :max-val [msg] - must be at most a certain value
- :within [msg] - must be within a certain range (inclusive)
- :positive [msg] - must be a positive number
- :negative [msg] - must be a negative number
- :after [msg] - must be after a certain date
- :before [msg] - must be before a certain date
- :in [msg] - must be contained within a collection
- :every-in [msg] - each value must be within a collection (for values that are themselves collections)
- :us-zip [msg] - must be a valid US zip code
- :luhn [msg] - must be pass the Luhn check (e.g., for credit card numbers)
- Datatype validations: :string, :boolean, :integer, :float, :decimal, :date (plus aliases)
- Datatype collection validations: :strings, :booleans, :integers, :floats, :decimals, :dates (plus aliases)
This library uses verily under the hood.
cd validator && make test
MIT
Create an issue, star it, make a pull request, there are no rules. Anarchy contribution.