How to Associate Custom Messages with Spec Violations?

I’d like to leverage the spec library to validate form input. The idea is to update values in re-frame’s db, validate against spec, and display the corresponding error message. While explain-data get me close, it doesn’t quite provide the functionality I need. With the following example, I understand that the issue is the missing ::last-name, but that’s more involved to programmatically determine. Does anyone know of a way to achieve the desired goal? Thanks.

(require '[cljs.spec.alpha :as s])

(s/def ::first-name string?)

(s/def ::last-name string?)

(s/def ::person (s/keys :req [::first-name ::last-name]))

(def p1 {::first-name "Ari"})

(:cljs.spec.alpha/problems (s/explain-data ::person p1))

Take a look at https://github.com/alexanderkiel/phrase

spec-tools also has something for this: the :reason spec property is attached to errors: https://cljdoc.org/d/metosin/spec-tools/0.10.1/doc/spec-records#custom-errors

1 Like

While I can appreciate the ingenuity, I cannot help but think this is a ugly, ugly hack.

For form validations, I tend to prefer Prismatic Schema or metosin/malli. All spec solutions to custom error messages / coercers / form validations seem too hacky and too dependent of internal state (that will probably change with specs2).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.