Using Prismatic / schema to validate a form with Liberator
Is Prismatic / schema suitable for form validation? I've never developed a version of form validation before, but my guess is that it outputs something like this rather than throwing exceptions on s/validate
:
{::errors {:name [{:missing "Required field."}
{:length "Must be at least 3 characters."}]
:email [{:email "Must be a valid email address"}]}}
I hope someone has used it with Compojure and Liberator, but I can't find anything on the internet.
source to share
Found some great helpers on Dante on GitHub , but the license to use is not clear:
(ns dante.tools.schemas
(:require [dante.tools.namespaces :refer [export]]
[schema.core :as s]
[schema.coerce :as coerce]
[schema.utils :refer [validation-error-explain]])
(:import [schema.utils NamedError ValidationError]))
(defn explain [errors]
(cond
(map? errors)
(->> errors
(map (fn [[k v]]
[k (explain v)]))
(into {}))
(or (seq? errors)
(coll? errors))
(map explain errors)
(instance? NamedError errors)
[(.name errors)
(explain (.error errors))]
(instance? ValidationError errors)
(str (validation-error-explain errors))
:else
(str errors)))
(defn- coercercions [schema]
(or
(coerce/+string-coercions+ schema)
(coerce/set-matcher schema)))
(defn validate [schema value]
((coerce/coercer schema coercercions) value))
source to share
From your description of the error map you want to get on validation failure looks like a Validator . Quoting from the Getting Started page:
Validateur is a validation library based on Ruby ActiveModel. Validateur is functional: validators are functions, validation sets are higher-order functions, and validation results are returned as values.
Around that little core, Validateur can be extended with any custom validator you might need: it's as simple as defining a Clojure function that follows a straightforward contract.
source to share