Skip to content

Commit

Permalink
Merge pull request #285 from Jetstar/maxlength_on_inputs
Browse files Browse the repository at this point in the history
Support for maxlength on string inputs inferred from validation
  • Loading branch information
rafaelfranca committed Jul 21, 2011
2 parents 14b6263 + 51a8497 commit bf01de6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/simple_form/inputs/string_input.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ class StringInput < Base

def input
input_html_options[:size] ||= [limit, SimpleForm.default_input_size].compact.min
input_html_options[:maxlength] ||= maximum_length_from_validation
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

Expand All @@ -37,6 +37,17 @@ def string?
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]
end

def find_length_validator
attribute_validators.find { |v| ActiveModel::Validations::LengthValidator === v }
end
end
end
end
5 changes: 5 additions & 0 deletions test/inputs_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,11 @@ def with_input_for(object, attribute_name, type, options={})
assert_select 'input.password[type=password][maxlength=100]'
end

test 'input should infer maxlength column definition from validation when present' do
with_input_for @validating_user, :name, :string
assert_select 'input.string[maxlength=25]'
end

test 'when not using HTML5, does not show maxlength attribute' do
swap SimpleForm, :html5 => false do
with_input_for @user, :password, :password
Expand Down
1 change: 1 addition & 0 deletions test/support/models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit bf01de6

Please sign in to comment.