Skip to content

Instantly share code, notes, and snippets.

@alexanderkiel
Created January 17, 2018 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderkiel/cfc57785b2c87ac71af6bffb792f8251 to your computer and use it in GitHub Desktop.
Save alexanderkiel/cfc57785b2c87ac71af6bffb792f8251 to your computer and use it in GitHub Desktop.
Example of Phrase for Map Validation
#!/usr/bin/env planck -D phrase:0.3-alpha2
(require '[clojure.spec.alpha :as s])
(require '[phrase.alpha :refer [defphraser phrase]])
(s/def ::required-string (s/and string? not-empty))
(s/def ::name ::required-string)
(s/def ::phone (s/and string? #(re-matches #"(\+47)?\d+" %)))
(s/def ::email (s/and string? #(re-matches #".+@.+" %)))
(s/def ::first-name ::name)
(s/def ::last-name ::name)
(s/def ::orderer (s/keys :req-un [::first-name ::last-name ::email ::phone]))
(defphraser #(re-matches _ %)
{:via [::phone]}
[_ _]
"Invalid phone number.")
(defphraser #(re-matches _ %)
{:via [::email]}
[_ _]
"Invalid email.")
(def invalid-orderer
{:first-name "asdf"
:last-name "hello"
:email "asdf"
:phone "hello"})
(->> (s/explain-data ::orderer invalid-orderer)
::s/problems
(map #(assoc % :msg (phrase nil %)))
(reduce (fn [r {:keys [path msg]}]
(assoc r (first path) msg)) {})
(println))
@alexanderkiel
Copy link
Author

  • install planck
  • download phrase-map-01.cljs
  • run:
chmod +x phrase-map-01.cljs 
./phrase-map-01.cljs 
  • should output:
{:email Invalid email., :phone Invalid phone number.}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment