From c00c2bb44fbeb012f2911fc7b41912011a4ef740 Mon Sep 17 00:00:00 2001 From: Michael Wu Date: Sat, 4 Aug 2012 01:31:00 -0400 Subject: [PATCH] Allow key to be function so a predicate can check more than one value in the map. --- project.clj | 4 ++-- src/valip/core.clj | 14 ++++++++++---- test/valip/test/core.clj | 7 +++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/project.clj b/project.clj index d17dc21..5fe6414 100644 --- a/project.clj +++ b/project.clj @@ -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"]]) diff --git a/src/valip/core.clj b/src/valip/core.clj index 34e2803..ab66a9e 100644 --- a/src/valip/core.clj +++ b/src/valip/core.clj @@ -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 @@ -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)) diff --git a/test/valip/test/core.clj b/test/valip/test/core.clj index 4627d07..c1dc337 100644 --- a/test/valip/test/core.clj +++ b/test/valip/test/core.clj @@ -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"]))))