Set the min attribute when there's a >= validation

This commit is contained in:
Daniel Schierbeck 2010-09-05 23:19:45 +08:00 committed by Carlos Antonio da Silva
parent b5502ea786
commit c81f3ca994
4 changed files with 28 additions and 1 deletions

View File

@ -9,12 +9,32 @@ module SimpleForm
input_options = super
input_options[:type] ||= "number"
input_options[:size] ||= SimpleForm.default_input_size
infer_attrs_from_validations(input_options)
input_options
end
def input_html_classes
super.unshift("numeric")
end
protected
def infer_attrs_from_validations(input_options)
obj = @builder.object
return unless obj.class.respond_to?(:validators_on)
validators = obj.class.validators_on(attribute_name)
num_validator = validators.find {|v| v.is_a?(ActiveModel::Validations::NumericalityValidator) }
return if num_validator.nil?
options = num_validator.__send__(:options)
input_options[:min] ||= options[:greater_than_or_equal_to]
end
end
end
end
end

View File

@ -54,6 +54,11 @@ class InputTest < ActionView::TestCase
assert_select 'input[type=number].integer#user_age'
end
test 'input should generate a min attribute when such a validation exists in the model' do
with_input_for @validating_user, :age, :integer
assert_select 'input[min=18]'
end
test 'input should generate a float text field for float attributes ' do
with_input_for @user, :age, :float
assert_select 'input[type=number].float#user_age'

View File

@ -118,4 +118,5 @@ class ValidatingUser < User
include ActiveModel::Validations
validates :name, :presence => true
validates :company, :presence => true
validates_numericality_of :age, :greater_than_or_equal_to => 18
end

View File

@ -60,6 +60,7 @@ class ActionView::TestCase
:name => 'New in Simple Form!',
:description => 'Hello!',
:created_at => Time.now,
:age => 19,
:company => 1
}.merge(options))
end