theleoborges / bouncer

A validation DSL for Clojure & Clojurescript applications
364 stars 38 forks source link

No way to validate a combination of fields. #20

Closed mogverse closed 10 years ago

mogverse commented 10 years ago

For example: I have to check a "from" key should be less than "to" key for a range value. I have to write a custom validator and pass the to field from the dictionary as the second parameter for the validator that gets applied to the older field.

Sometimes we have checks like if key A is present then key B should be present.

Can there be support at DSL level to specify such rules ?

theleoborges commented 10 years ago

Pre-conditions can help you with your second example:

(b/validate {}
            :b [[v/required :pre (comp not nil? :a)]])
;; [nil {}]

(b/validate {:a "ImAValue"}
            :b [[v/required :pre (comp not nil? :a)]])

;; [{:b ("b must be present")} {:bouncer.core/errors {:b ("b must be present")}, :a "ImAValue"}]

Unfortunately the first case - ensuring from is less than to - isn't supported at the moment. It is on my to-do list however. I'm thinking about how to best support it. It would allow other things such as password confirmation to be validated easily too.

Having said that, my workaround would be this:

(def subject {:from 20 :to 10})

(defn less-than [max]
  (fn [value]
    (< value max)))

(b/validate subject
            :from [[(less-than (:to subject)) :pre (comp not nil? :to)]]
            :to   [[v/required]])

Which is along the lines of what you suggested, though I haven't seen your implementation.

This would only validate from if to is also present. And possibly a number as well.

theleoborges commented 10 years ago

Closing this issue as the second use case is handled by Pre-conditions and the first use case is being discussed on issue #21