Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions project.clj
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
(defproject valip "0.2.0"
:description "Functional validation library"
:dependencies [[org.clojure/clojure "1.2.0"]
:dependencies [[org.clojure/clojure "1.3.0"]
[commons-validator "1.3.1"]
[clj-time "0.3.0"]])
[clj-time "0.4.0"]])
14 changes: 10 additions & 4 deletions src/valip/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
"Performs a validation on a key in a map using the supplied predicate
function. A {key [error]} map is returned if the predicate returns false;
nil is returned if the predicate returns true, or if the supplied value does
not match the predicates preconditions (i.e. throws an AssertionError)."
not match the predicates preconditions (i.e. throws an AssertionError).

Key may be a function taking a map and returning a value.
It's error would be associated with :* in the error map."
[key pred? error]
(fn [value-map]
(let [value (value-map key)]
(let [value (key value-map)]
(try
(if-not (pred? value)
{key [error]})
{(if (keyword? key) key :*) [error]})
(catch AssertionError _)))))

(defn merge-errors
Expand All @@ -23,7 +26,10 @@
"Validate a map of values using the supplied validations. Each validation
is represented as a vector containing [key predicate? error] values. A map
is returned for all the keys that failed their predicates, in the form:
{key [errors]}. If no predicates return false, nil is returned."
{key [errors]}. If no predicates return false, nil is returned.

A validation key may be a function taking a map and returning a value.
It's error would be associated with :* key in the error map."
[value-map & validations]
(->> validations
(map (partial apply validation-on))
Expand Down
7 changes: 7 additions & 0 deletions test/valip/test/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,10 @@
[:x #(> % 18) "must be greater than 18"])
{:x ["must be greater than 18"]
:y ["must be present"]})))

(deftest validate-key-as-fn
(is (= (validate {:password "secret" :confirm-password ""}
[identity #(apply = (map % [:password :confirm-password])) "passwords must match"])
{:* ["passwords must match"]}))
(is (nil? (validate {:password "secret" :confirm-password "secret"}
[#(map % [:password :confirm-password]) #(apply = %) "passwords must match"]))))