Created
January 17, 2018 15:01
-
-
Save alexanderkiel/cfc57785b2c87ac71af6bffb792f8251 to your computer and use it in GitHub Desktop.
Example of Phrase for Map Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
phrase-map-01.cljs