discourse/lib/validators/email_address_validator.rb
Bianca Nenciu d82fcb8af8
Some checks are pending
Licenses / run (push) Waiting to run
Linting / run (push) Waiting to run
Publish Assets / publish-assets (push) Waiting to run
Tests / core backend (push) Waiting to run
Tests / plugins backend (push) Waiting to run
Tests / core frontend (Chrome) (push) Waiting to run
Tests / plugins frontend (push) Waiting to run
Tests / themes frontend (push) Waiting to run
Tests / core system (push) Waiting to run
Tests / plugins system (push) Waiting to run
Tests / themes system (push) Waiting to run
Tests / core frontend (Firefox ESR) (push) Waiting to run
Tests / core frontend (Firefox Evergreen) (push) Waiting to run
Tests / chat system (push) Waiting to run
Tests / merge (push) Blocked by required conditions
FIX: Validate email length (#34786)
* The maximum total length of a user name or other local-part is 64
octets.

* The maximum total length of a domain name or number is 255 octets.
2025-09-11 18:58:07 +03:00

36 lines
1,023 B
Ruby

# frozen_string_literal: true
class EmailAddressValidator
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/
ENCODED_WORD_REGEX = /\=\?[^?]+\?[BbQq]\?[^?]+\?\=/
class << self
def valid_value?(email)
# '@' splits the email in two parts local@domain
# local part must be <= 64 characters
# domain part must be <= 255 characters
at_index = email.to_s.index("@")
!!at_index && at_index <= 64 && (email.length - at_index - 1) <= 255 &&
email.match?(email_regex) && !email.match?(encoded_word_regex) &&
decode(email)&.match?(email_regex)
end
def email_regex
EMAIL_REGEX
end
def encoded_word_regex
ENCODED_WORD_REGEX
end
private
def decode(email)
Mail::Address.new(email).decoded
rescue Mail::Field::ParseError, Mail::Field::IncompleteParseError
nil
end
end
end