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.

+3


source to share


3 answers


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))

      

0


source


I've been using Schema to validate common form (ClojureScript) and server side (Clojure) for some time now and it worked out very well.

I originally posted a suggestion to use the schema on GitHub:



Link here

Let me know if you would like more examples.

0


source


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.

0


source







All Articles