Skip to content

Commit b96bc56

Browse files
committed
Item.validates_length_of ..., {minimum: } to minlength attribute
1 parent 13a1be5 commit b96bc56

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

lib/html5_validators/action_view/form_helpers.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ module LengthValidator
2424
def render
2525
if object.class.ancestors.include?(ActiveModel::Validations) && (object.auto_html5_validation != false) && (object.class.auto_html5_validation != false)
2626
@options["maxlength"] ||= @options[:maxlength] || object.class.attribute_maxlength(@method_name)
27+
@options["minlength"] ||= @options[:minlength] || object.class.attribute_minlength(@method_name)
2728
end
2829
super
2930
end

lib/html5_validators/active_model/helper_methods.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ def attribute_maxlength(attribute)
1313
}.map {|v| v.options.slice(:maximum, :is)}.map(&:values).flatten.max
1414
end
1515

16+
def attribute_minlength(attribute)
17+
self.validators.grep(LengthValidator).select {|v|
18+
v.attributes.include?(attribute.to_sym) && (v.options.keys & [:minimum, :is]).any? && (v.options.keys & [:if, :unless, :allow_nil, :allow_blank, :tokenizer]).empty?
19+
}.map {|v| v.options.slice(:minimum, :is)}.map(&:values).flatten.min
20+
end
21+
1622
def attribute_max(attribute)
1723
self.validators.grep(NumericalityValidator).select {|v|
1824
v.attributes.include?(attribute.to_sym) && (v.options.keys & [:less_than, :less_than_or_equal_to]).any? && (v.options.keys & [:if, :unless, :allow_nil, :allow_blank]).empty?

spec/features/validation_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,20 @@
8686
find('textarea#person_bio')[:maxlength].should == '100'
8787
end
8888
end
89+
90+
context 'with minlength validation' do
91+
background do
92+
Person.validates_length_of :name, {:minimum => 3}
93+
Person.validates_length_of :bio, {:minimum => 10}
94+
end
95+
96+
scenario 'new form' do
97+
visit '/people/new'
98+
99+
find('input#person_name')[:minlength].should == '3'
100+
find('textarea#person_bio')[:minlength].should == '10'
101+
end
102+
end
89103
end
90104

91105
feature 'item#new' do
@@ -174,4 +188,18 @@
174188
find('textarea#item_description')[:maxlength].should == '100'
175189
end
176190
end
191+
192+
context 'with minlength validation' do
193+
background do
194+
Item.validates_length_of :name, {:minimum => 3}
195+
Item.validates_length_of :description, {:minimum => 10}
196+
end
197+
198+
scenario 'new form' do
199+
visit '/items/new'
200+
201+
find('input#item_name')[:minlength].should == '3'
202+
find('textarea#item_description')[:minlength].should == '10'
203+
end
204+
end
177205
end

0 commit comments

Comments
 (0)