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 Jul 2, 2024
1 parent 987b9f9 commit c7d4d8e
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#### Features

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

#### Fixes
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1713,6 +1713,7 @@ end
#### `length`

Parameters with types that support `#length` method can be restricted to have a specific length with the `:length` option.
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.

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

Expand Down
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
requires :list, type: [Integer], length: { min: 2 }
end
post '/nil_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 '/nil_param' do
context 'no raises errors' do
it do
expect do
post '/nil_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 c7d4d8e

Please sign in to comment.