Skip to content

Commit

Permalink
Merge pull request #492 from reevoo/validate_nil_value_in_values_vali…
Browse files Browse the repository at this point in the history
…dator

Don't allow to have nil value when required & have allowed values.
  • Loading branch information
dblock committed Oct 24, 2013
2 parents ea01a86 + 177a14c commit 34e6013
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ Next Release

* Your contribution here.

#### Fixes

* [#492](https://github.com/intridea/grape/pull/492): Don't allow to have nil value when a param is required and has a list of allowed values. - [@Antti](https://github.com/Antti)

0.6.1
=====

Expand Down
3 changes: 2 additions & 1 deletion lib/grape/validations/values.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ module Validations
class ValuesValidator < Validator
def initialize(attrs, options, required, scope)
@values = options
@required = required
super
end

def validate_param!(attr_name, params)
if params[attr_name] && !@values.include?(params[attr_name])
if (params[attr_name] || @required) && !@values.include?(params[attr_name])
raise Grape::Exceptions::Validation, param: @scope.full_name(attr_name), message_key: :values
end
end
Expand Down
6 changes: 6 additions & 0 deletions spec/grape/validations/values_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ def app
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
end

it 'does not allow nil value for a parameter' do
get("/", type: nil)
last_response.status.should eq 400
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
end

it 'allows a valid default value' do
get("/default/valid")
last_response.status.should eq 200
Expand Down

0 comments on commit 34e6013

Please sign in to comment.