Skip to content

Commit c7d4d8e

Browse files
committed
length validator allow nil
1 parent 987b9f9 commit c7d4d8e

File tree

4 files changed

+20
-0
lines changed

4 files changed

+20
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#### Features
44

5+
* [#2464](https://github.com/ruby-grape/grape/pull/2464): Length validator allow nil - [@OuYangJinTing](https://github.com/OuYangJinTing).
56
* Your contribution here.
67

78
#### Fixes

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1713,6 +1713,7 @@ end
17131713
#### `length`
17141714

17151715
Parameters with types that support `#length` method can be restricted to have a specific length with the `:length` option.
1716+
In addition, if the received parameter value is nil, the length validation will not be triggered. If you do not allow nil, you can use the `allow_blank: false` option.
17161717

17171718
The validator accepts `:min` or `:max` or both options to validate that the value of the parameter is within the given limits.
17181719

lib/grape/validations/validators/length_validator.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ def initialize(attrs, options, required, scope, **opts)
1818
def validate_param!(attr_name, params)
1919
param = params[attr_name]
2020

21+
return if param.nil?
22+
2123
raise ArgumentError, "parameter #{param} does not support #length" unless param.respond_to?(:length)
2224

2325
return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max)

spec/grape/validations/validators/length_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@
8181
post 'zero_max' do
8282
end
8383

84+
params do
85+
requires :list, type: [Integer], length: { min: 2 }
86+
end
87+
post '/nil_param' do
88+
end
89+
8490
params do
8591
requires :list, type: [Integer], length: { min: 2, message: 'not match' }
8692
end
@@ -187,6 +193,16 @@
187193
end
188194
end
189195

196+
describe '/nil_param' do
197+
context 'no raises errors' do
198+
it do
199+
expect do
200+
post '/nil_param', list: nil
201+
end.not_to raise_error
202+
end
203+
end
204+
end
205+
190206
describe '/type_is_not_array' do
191207
context 'raises an error' do
192208
it do

0 commit comments

Comments
 (0)