diff --git a/CHANGELOG.md b/CHANGELOG.md index fb34e9846b..9a5d3f0cf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 3be2dcead9..9b18f2c761 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/lib/grape/validations/validators/length_validator.rb b/lib/grape/validations/validators/length_validator.rb index bcd0c95592..78ea580988 100644 --- a/lib/grape/validations/validators/length_validator.rb +++ b/lib/grape/validations/validators/length_validator.rb @@ -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) diff --git a/spec/grape/validations/validators/length_spec.rb b/spec/grape/validations/validators/length_spec.rb index 8fa9f84876..3b0861b392 100644 --- a/spec/grape/validations/validators/length_spec.rb +++ b/spec/grape/validations/validators/length_spec.rb @@ -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 @@ -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