Skip to content

Commit

Permalink
Merge pull request #178 from vkononov/bug-support-email-array
Browse files Browse the repository at this point in the history
Fix an issue with validating an email array
  • Loading branch information
micke authored Jun 26, 2021
2 parents 4f58aee + 2e61ea2 commit 2782fdf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/valid_email2/email_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ def validate_each(record, attribute, value)
return unless value.present?
options = default_options.merge(self.options)

value_spitted = options[:multiple] ? value.split(',').map(&:strip) : [value]
addresses = value_spitted.map { |v| ValidEmail2::Address.new(v) }
addresses = sanitized_values(value).map { |v| ValidEmail2::Address.new(v) }

error(record, attribute) && return unless addresses.all?(&:valid?)

Expand Down Expand Up @@ -54,6 +53,18 @@ def validate_each(record, attribute, value)
end
end

def sanitized_values(input)
options = default_options.merge(self.options)

if options[:multiple]
email_list = input.is_a?(Array) ? input : input.split(',')
else
email_list = [input]
end

email_list.reject(&:empty?).map(&:strip)
end

def error(record, attribute)
record.errors.add(attribute, options[:message] || :invalid)
end
Expand Down
5 changes: 5 additions & 0 deletions spec/valid_email2_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,11 @@ def set_whitelist
expect(user.valid?).to be_truthy
end

it "tests each address from an array" do
user = TestUserMultiple.new(email: %w[foo@gmail.com bar@gmail.com])
expect(user.valid?).to be_truthy
end

context 'when one address is invalid' do
it "fails for all" do
user = TestUserMultiple.new(email: "foo@gmail.com, bar@123")
Expand Down

0 comments on commit 2782fdf

Please sign in to comment.