diff --git a/lib/simple_form/inputs/string_input.rb b/lib/simple_form/inputs/string_input.rb index be29fa92..728242e4 100644 --- a/lib/simple_form/inputs/string_input.rb +++ b/lib/simple_form/inputs/string_input.rb @@ -8,6 +8,7 @@ module SimpleForm def input input_html_options[:size] ||= [limit, SimpleForm.default_input_size].compact.min + input_html_options[:pattern] ||= pattern_validator if validate_pattern? if password? || SimpleForm.html5 input_html_options[:type] ||= input_type unless string? end @@ -35,6 +36,20 @@ module SimpleForm def password? input_type == :password end + + def validate_pattern? + return unless has_validators? + + SimpleForm.html5 && SimpleForm.browser_validations && find_pattern_validator.present? + end + + def pattern_validator + find_pattern_validator.options[:with].source + end + + def find_pattern_validator + attribute_validators.find { |v| ActiveModel::Validations::FormatValidator === v } + end end end end diff --git a/test/inputs_test.rb b/test/inputs_test.rb index 2cd001e5..188139d7 100644 --- a/test/inputs_test.rb +++ b/test/inputs_test.rb @@ -323,6 +323,30 @@ class InputTest < ActionView::TestCase assert_select 'input[max=119]' end + test 'input should infer pattern from attributes when it is present' do + with_input_for @other_validating_user, :country, :string + assert_select 'input[pattern="\w+"]' + end + + test 'input should infer pattern from attributes when it is present as a password' do + with_input_for @other_validating_user, :country, :password + assert_select 'input[pattern="\w+"]' + end + + test 'input should not add pattern from attributes when html5 are turned off' do + swap SimpleForm, :html5 => false do + with_input_for @other_validating_user, :country, :password + assert_no_select 'input[pattern="\w+"]' + end + end + + test 'input should not add pattern from attributes when browser validations are turned off' do + swap SimpleForm, :browser_validations => false do + with_input_for @other_validating_user, :country, :password + assert_no_select 'input[pattern="\w+"]' + end + end + test 'input should have step value of any except for integer attribute' do with_input_for @validating_user, :age, :float assert_select 'input[step="any"]' diff --git a/test/support/models.rb b/test/support/models.rb index 06d7489e..c3440c5e 100644 --- a/test/support/models.rb +++ b/test/support/models.rb @@ -177,6 +177,8 @@ class OtherValidatingUser < User :greater_than_or_equal_to => Proc.new { |user| user.age }, :less_than_or_equal_to => Proc.new { |user| user.age + 100}, :only_integer => true + + validates_format_of :country, :with => /\w+/ end class HashBackedAuthor < Hash