Last active
January 23, 2016 21:40
-
-
Save mbakhterev/86c4ac21ced119a5e90c to your computer and use it in GitHub Desktop.
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
(ns try-cljs.shopping.validators | |
(:require [valip.core :refer [validate]] | |
[valip.predicates :refer [present? | |
integer-string? | |
decimal-string? | |
gt]])) | |
(defn- empty-checks [] | |
(map (fn [x] [(keyword x) 'present? (str x " can't be empty")]) | |
'("quantity" "price" "tax" "discount"))) | |
(defn- number-checks [] | |
(map (fn [x] [(keyword x) | |
'decimal-string? | |
(str x " should be a number")]) | |
'("price" "tax" "discount"))) | |
(defn- quantity-checks [] | |
(list [:quantity 'integer-string? "quantity should be an integer"] | |
[:quantity '(gt 0) "quantity should be positive"])) | |
(defn- checks-fn [] (concat (empty-checks) | |
(number-checks) | |
(quantity-checks))) | |
(defmacro check-list [] (checks-fn)) | |
(defmacro validate-macro [V C] | |
(do (println "expanding" &form) | |
(println `(validate ~V ~@(macroexpand C)))) | |
`(validate ~V ~@(macroexpand C))) | |
(defn validate-shopping-form [q p t d] | |
(validate-macro {:quantity q :price p :tax t :discount d} | |
(check-list))) | |
(println (macroexpand '(validate-macro {} (check-list)))) |
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
(defn validate-shopping-form [quantity price tax discount] | |
(validate {:quantity quantity :price price :tax tax :discount discount} | |
;; validate presence | |
[:quantity present? "Quantity can't be empty"] | |
[:price present? "Price can't be empty"] | |
[:tax present? "Tax can't be empty"] | |
[:discount present? "Discount can't be empty"] | |
;; validate type | |
[:quantity integer-string? "Quantity has to be an integer number"] | |
[:price decimal-string? "Price has to be a number"] | |
[:tax decimal-string? "Tax has to be a number"] | |
[:discount decimal-string? "Discount has to be a number"] | |
;; validate range | |
[:quantity (gt 0) "Quantity can't be negative"] | |
;; other specific platform validations (not at the moment) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment