support for maxlength on string inputs infered from validation which takes presedence over database column metadata

This commit is contained in:
Stephen Bartlett 2011-07-17 21:15:36 +10:00
parent b43fac90e0
commit 43677ef053
3 changed files with 21 additions and 1 deletions

View File

@ -8,11 +8,12 @@ module SimpleForm
def input
input_html_options[:size] ||= [limit, SimpleForm.default_input_size].compact.min
preferred_max_length = maximum_length_from_validation
input_html_options[:maxlength] ||= preferred_max_length if preferred_max_length
input_html_options[:maxlength] ||= limit if limit && SimpleForm.html5
if password? || SimpleForm.html5
input_html_options[:type] ||= input_type unless string?
end
@builder.send(input_method, attribute_name, input_html_options)
end
@ -37,6 +38,17 @@ module SimpleForm
def password?
input_type == :password
end
def maximum_length_from_validation
return unless has_validators?
length_validator = find_length_validator or return
length_validator.options[:maximum] if length_validator.options.key? :maximum
end
def find_length_validator
attribute_validators.find { |v| ActiveModel::Validations::LengthValidator === v }
end
end
end
end

View File

@ -166,6 +166,13 @@ class InputTest < ActionView::TestCase
assert_select 'input.password[type=password][maxlength=100]'
end
test 'when not using HTML5, should infer maxlength column definition from validation when present' do
swap SimpleForm, :html5 => false do
with_input_for @validating_user, :name, :string
assert_select 'input.string[maxlength=25]'
end
end
test 'when not using HTML5, does not show maxlength attribute' do
swap SimpleForm, :html5 => false do
with_input_for @user, :password, :password

View File

@ -141,6 +141,7 @@ class ValidatingUser < User
:greater_than_or_equal_to => :min_attempts,
:less_than_or_equal_to => :max_attempts,
:only_integer => true
validates_length_of :name, :maximum => 25
def min_amount
10