theleoborges / bouncer

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

There should be a way to avoid validation for optional keys #19

Closed mogverse closed 10 years ago

mogverse commented 10 years ago
(b/validate contact-details                                                                                                      
                           "email" [[v/required :message "Email is required"]]                                                                      
                           "phone_number"  [[v/matches  #"^\d{10}$" :message "Phone number should be a numeric value of 10 digit."]])

Now email is required and phone number is optional but in case phone number is present I need to verify its pattern.

Now with the regular flow, if I don't add required to the phone number field then it checks the nil value to match with the pattern.

There should be a way in the DSL to avoid a validator if the data is not present otherwise one has to write custom validators with extra check and can't re-use existing in built validators.

Suggestion: if a validator's name starts with a special character then it can be considered optional ?

theleoborges commented 10 years ago

Hi,

I'm not sure I understand your comment fully but the behaviour seems to be correct:

If I don't provide a phone number, it is not validated as matches is optional:

(b/validate {:email "leo@leo.com"}
            :email [[v/required :message "Email is required"]]
            :phone_number  [[v/matches  #"^\d{10}$" :message "Phone number should be a numeric value of 10 digit."]])

;; [nil {:email "leo@leo.com"}]

On the other hand if I do provide a number, only then it is matched against the validator:

(b/validate {:email "leo@leo.com"
             :phone_number "notANumber"}
            :email [[v/required :message "Email is required"]]
            :phone_number  [[v/matches  #"^\d{10}$" :message "Phone number should be a numeric value of 10 digit."]])

;; [{:phone_number ("Phone number should be a numeric value of 10 digit.")} {:bouncer.core/errors {:phone_number ("Phone number should be a numeric value of 10 digit.")}, :email "leo@leo.com", :phone_number "notANumber"}]

Let me know if this is not what you meant.

theleoborges commented 10 years ago

Hi @amogh-talpallikar ,

I haven't heard from you in a while so I'm assuming this isn't an issue for you any longer.

Please re-open the issue if that is not the case.

mogverse commented 10 years ago

@leonardoborges : Yeah. I realized. actually it was aptoblem with some of our own validators that were using regex checks, we added logic in those to avoid validation if data is not present.

Also pre-conditions are helping here also. Never knew about preconditions at that time.

theleoborges commented 10 years ago

Glad to hear it :)