Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

validates_length with minimum 0 and allow_nil: false accept nil

Given a class that include ActiveModel::Validations with a validation like the following:
validates_length_of(:title, :minimum => 0, :allow_nil => false).
This makes incosistent the validation because it not raise error when
title is *nil*.It should accepts only the empty string
With this patch title is *nil* is handled and the validation accepts only the empty string *""*
It should fix #7180
  • Loading branch information...
commit 94e2c2cd2398ec0fa4c1d2466e59d2a59871c46d 1 parent 10cdeb8
@acapilleri authored
View
13 activemodel/lib/active_model/validations/length.rb
@@ -38,10 +38,12 @@ def validate_each(record, attribute, value)
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
CHECKS.each do |key, validity_check|
- next unless check_value = options[key]
- next if value_length.send(validity_check, check_value)
+ unless min_zero_val_nil_allow_nil_false?(options, value)
+ next unless check_value = options[key]
+ next if value_length.send(validity_check, check_value)
+ end
- errors_options = options.except(*RESERVED_OPTIONS)
+ errors_options ||= options.except(*RESERVED_OPTIONS)
errors_options[:count] = check_value
default_message = options[MESSAGES[key]]
@@ -53,6 +55,11 @@ def validate_each(record, attribute, value)
private
+ def min_zero_val_nil_allow_nil_false?(options, value)
+ empty_string_is_allowed ||= options[:minimum] == 0 && value.nil? && options[:allow_nil] == false
+ empty_string_is_allowed
+ end
+
def tokenize(value)
if options[:tokenizer] && value.kind_of?(String)
options[:tokenizer].call(value)
View
13 activemodel/test/cases/validations/length_validation_test.rb
@@ -375,4 +375,17 @@ def test_validates_length_of_for_infinite_maxima
t.author_name = "A very long author name that should still be valid." * 100
assert t.valid?
end
+
+ def test_validates_length_of_with_minimum_zero_and_allow_nil
+ Topic.validates_length_of(:title, :minimum => 0, :allow_nil => false)
+
+ t = Topic.new(:title=>"1")
+ assert t.valid?
+
+ t = Topic.new(:title=>"")
+ assert t.valid?
+
+ t = Topic.new
+ assert t.invalid?
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.