DEV: pull email address validation out to a new EmailAddressValidator

We validate the *format* of email addresses in many places with a match against
a regex, often with very slightly different syntax.

Adding a separate EmailAddressValidator simplifies the code in a few spots and
feels cleaner.

Deprecated the old location in case someone is using it in a plugin.

No functionality change is in this commit.

Note: the regex used at the moment does not support using address literals, e.g.:
* localpart@[192.168.0.1]
* localpart@[2001:db8::1]
This commit is contained in:
Michael Brown
2022-02-17 20:12:51 -05:00
committed by Michael Brown
parent e54b70460e
commit 3bf3b9a4a5
16 changed files with 51 additions and 31 deletions

View File

@ -0,0 +1,11 @@
# frozen_string_literal: true
class EmailAddressValidator
def self.valid_value?(email)
email.match? email_regex
end
def self.email_regex
/\A[a-zA-Z0-9!#\$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-zA-Z0-9!#\$%&'\*+\/=?\^_`{|}~\-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$\z/
end
end

View File

@ -6,7 +6,8 @@ class EmailSettingValidator
end
def valid_value?(val)
!val.present? || !!(EmailValidator.email_regex =~ val)
return true if val.blank?
EmailAddressValidator.valid_value?(val)
end
def error_message

View File

@ -3,7 +3,7 @@
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ EmailValidator.email_regex
if !EmailAddressValidator.valid_value?(value)
if Invite === record && attribute == :email
record.errors.add(:base, I18n.t(:'invite.invalid_email', email: CGI.escapeHTML(value)))
else
@ -12,7 +12,7 @@ class EmailValidator < ActiveModel::EachValidator
invalid = true
end
unless EmailValidator.allowed?(value)
if !EmailValidator.allowed?(value)
record.errors.add(attribute, I18n.t(:'user.email.not_allowed'))
invalid = true
end
@ -51,7 +51,11 @@ class EmailValidator < ActiveModel::EachValidator
end
def self.email_regex
/\A[a-zA-Z0-9!#\$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-zA-Z0-9!#\$%&'\*+\/=?\^_`{|}~\-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$\z/
Discourse.deprecate(
"EmailValidator.email_regex is deprecated. Please use EmailAddressValidator instead.",
output_in_test: true,
drop_from: '2.9.0',
)
EmailAddressValidator.email_regex
end
end