Created
May 25, 2018 03:14
-
-
Save ryanthames/086ff7b9f0712c40fa8489d6c8bef19e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(def order-details | |
{:name "Mitchard Blimmons" | |
:email "mitchard.blimmonsgmail.com"}) | |
(def order-details-validations | |
{:name | |
["Please enter a name" not-empty] | |
["Please enter an email address" not-empty | |
"Your email address doesn't look like an email address" | |
#(or (empty? %) (re-seq #"@" %))]}) | |
(defn error-messages-for | |
"Return a seq of error messages" | |
[to-validate message-validator-pairs] | |
(map first (filter #(not ((second %) to-validate)) | |
(partition 2 message-validator-pairs)))) | |
; (error-messages-for "" ["Please enter a name" not-empty]) | |
(defn validate | |
"Returns a map with a vector of errors for each key" | |
[to-validate validations] | |
(reduce (fn [errors validation] | |
(let [[fieldname validation-check-groups] validation | |
value (get to-validate fieldname) | |
error-messages (error-messages-for value validation-check-groups)] | |
(if (empty? error-messages) | |
errors | |
(assoc errors fieldname error-messages)))) | |
{} | |
validations)) | |
; (validate order-details order-details-validations) | |
(let [errors (validate order-details order-details-validations)] | |
(if (empty? errors) | |
(println :success) | |
(println :failure errors))) | |
(defmacro if-valid | |
"Handle validation more concisely" | |
[to-validate validations errors-name & then-else] | |
`(let [~errors-name (validate ~to-validate ~validations)] | |
(if (empty? ~errors-name) | |
~@then-else))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment