Introducing clova, a small validation library for Clojure and ClojureScript.
TL;DR
I wrote a small validation library for Clojure and ClojureScript. It's "alright" and it's called clova, I'd appreciate any feedback over on GitHub.
About
clova is a small validation library written for Clojure and ClojureScript.
Existing libraries like Prismatic Schema offer much more functionality but that may not be what is required. clova focuses more on targeted validation, like checking if something is a url or an email address, instead of schematic validation.
clova supports ClojureScript to enable scenarios like server and client side sharing of validation logic. To do so it makes use of reader conditionals introduced in Clojure 1.7. Earlier versions used cljx but that is considered deprecated because of the language support for reader conditionals.
How to use
Add the following dependency to project.clj :dependencies
.
Pull in the core namespace (:require [clova.core :as core])
.
Define a validation set
Validation sets are pairs of keys to validate and the functions used to validate them.
They support nested map access and validation functions can have variadic arity.
Defining a validator
Validators are just functions with some meta data and are defined using the defvalidator macro.
You can make use of the key name, value and any arguments passed to the validator in the :default-message
. The only thing to consider is the ordering of arguments, when the validation message is formatted it will supply the values in the following order: 1. The key to validate, 2. The current value, 3. The arguments passed to the validator (in the order they are specified).
It is worth noting that using positional arguments of the format %1$s
in :default-message
is supported in Clojure only. The string format function used in ClojureScript goog.string.format
does not support them.
Using a validation set
Using a validation set is simple. Pass the validation set you want to use and the map you wish to validate.
Result is a map, including a valid? flag and a sequence of results.
You can view API documentation here.
Built in validators
clova includes the following validators as of v0.4.0.- between?
- email?
- greater?
- lesser?
- matches?
- negative?
- positive?
- post-code?
- not-nil?
- required?
- url?
- zip-code?
- length?
- longer?
- shorter?
- one-of?
- all?
- credit-card?
- numeric?
- stringy?
- date?
- before?
- after?
- =date?
- =?
Positives
- It is easy to create and test new validators, the built in validators are simple pure functions.
- Error messages are specific. For example, instead of "Age must be in the specified range" we get "Age is 10 but it should be between 18 and 30".
To do
* Custom validation messages, probably localisable.
- Make string interpolation for default messages more intuitive.
Alternatives
clova is still new and prone to change, plus I'm still learning Clojure. Here are a couple of alternatives that are more stable.