Skip to content

Commit

Permalink
length validator allow nil
Browse files Browse the repository at this point in the history
  • Loading branch information
OuYangJinTing committed Jun 28, 2024
1 parent 987b9f9 commit 33d25b7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/grape/validations/validators/length_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def initialize(attrs, options, required, scope, **opts)
def validate_param!(attr_name, params)
param = params[attr_name]

return if param.nil?

raise ArgumentError, "parameter #{param} does not support #length" unless param.respond_to?(:length)

return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max)
Expand Down
16 changes: 16 additions & 0 deletions spec/grape/validations/validators/length_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@
post 'zero_max' do
end

params do
optional :list, type: [Integer], length: { min: 2 }
end
post '/no_param' do
end

params do
requires :list, type: [Integer], length: { min: 2, message: 'not match' }
end
Expand Down Expand Up @@ -187,6 +193,16 @@
end
end

describe '/no_param' do
context 'no raises errors' do
it do
expect do
post '/no_param', list: nil
end.not_to raise_error
end
end
end

describe '/type_is_not_array' do
context 'raises an error' do
it do
Expand Down

0 comments on commit 33d25b7

Please sign in to comment.