Skip to content

Commit

Permalink
change ActiveRecordValidator
Browse files Browse the repository at this point in the history
- changed method to add error to the record by adding "error_code"
  • Loading branch information
h-0-b authored and afair committed Oct 12, 2023
1 parent 5ece4f9 commit 69ad226
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/email_address/active_record_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@ module EmailAddress
# * field: email,
# * fields: [:email1, :email2]
#
# * code: custom error code (default: :invalid_address)
# * message: custom error message (default: "Invalid Email Address")
#
# Default field: :email or :email_address (first found)
#
#
class ActiveRecordValidator < ActiveModel::Validator
def initialize(options = {})
@opt = options
Expand All @@ -35,10 +39,11 @@ def validate_email(r, f)
return if r[f].nil?
e = Address.new(r[f])
unless e.valid?
error_code = @opt[:code] || :invalid_address
error_message = @opt[:message] ||
Config.error_message(:invalid_address, I18n.locale.to_s) ||
"Invalid Email Address"
r.errors.add(f, error_message)
r.errors.add(f, error_code, message: error_message)
end
end
end
Expand Down
10 changes: 10 additions & 0 deletions test/activerecord/test_ar.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,21 @@ def test_validation
user = User.new(email: "Pat.Jones+ASDF#GMAIL.com")
assert_equal false, user.valid?
assert user.errors.messages[:email].first

user = User.new(email: "[email protected]")
assert_equal true, user.valid?
end
end

def test_validation_error_message
if RUBY_PLATFORM != "java" # jruby
user = User.new(alternate_email: "Pat.Jones+ASDF#GMAIL.com")
assert_equal false, user.valid?
assert user.errors.messages[:alternate_email].first.include?("Check your email")
assert_equal :some_error_code, user.errors.details[:alternate_email].first[:error]
end
end

def test_datatype
# Disabled JRuby checks... weird CI failures. Hopefully someone can help?
if RUBY_PLATFORM != "java" # jruby
Expand Down
3 changes: 3 additions & 0 deletions test/activerecord/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,13 @@ class User < ApplicationRecord
if defined?(ActiveRecord) && ::ActiveRecord::VERSION::MAJOR >= 5
attribute :email, :email_address
attribute :canonical_email, :canonical_email_address
attribute :alternate_email, :email_address
end

validates_with EmailAddress::ActiveRecordValidator,
fields: %i[email canonical_email]
validates_with EmailAddress::ActiveRecordValidator,
field: :alternate_email, code: :some_error_code, message: "Check your email"

def email=(email_address)
self[:canonical_email] = email_address
Expand Down

0 comments on commit 69ad226

Please sign in to comment.