Skip to content

Commit 34e6013

Browse files
committed
Merge pull request #492 from reevoo/validate_nil_value_in_values_validator
Don't allow to have nil value when required & have allowed values.
2 parents ea01a86 + 177a14c commit 34e6013

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ Next Release
33

44
* Your contribution here.
55

6+
#### Fixes
7+
8+
* [#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)
9+
610
0.6.1
711
=====
812

lib/grape/validations/values.rb

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ module Validations
33
class ValuesValidator < Validator
44
def initialize(attrs, options, required, scope)
55
@values = options
6+
@required = required
67
super
78
end
89

910
def validate_param!(attr_name, params)
10-
if params[attr_name] && !@values.include?(params[attr_name])
11+
if (params[attr_name] || @required) && !@values.include?(params[attr_name])
1112
raise Grape::Exceptions::Validation, param: @scope.full_name(attr_name), message_key: :values
1213
end
1314
end

spec/grape/validations/values_spec.rb

+6
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ def app
4141
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
4242
end
4343

44+
it 'does not allow nil value for a parameter' do
45+
get("/", type: nil)
46+
last_response.status.should eq 400
47+
last_response.body.should eq({ error: "type does not have a valid value" }.to_json)
48+
end
49+
4450
it 'allows a valid default value' do
4551
get("/default/valid")
4652
last_response.status.should eq 200

0 commit comments

Comments
 (0)