Module: Philiprehberger::EmailValidator::Syntax

Defined in:
lib/philiprehberger/email_validator/syntax.rb

Overview

RFC 5322 compliant email syntax validation.

Validates local part rules, domain rules, and length limits according to the relevant RFCs (5321, 5322).

Constant Summary collapse

MAX_EMAIL_LENGTH =

Maximum total length of an email address (RFC 5321).

254
MAX_LOCAL_LENGTH =

Maximum length of the local part (RFC 5321).

64
MAX_DOMAIN_LENGTH =

Maximum length of the domain part (RFC 5321).

253
MAX_LABEL_LENGTH =

Maximum length of a single domain label.

63
LOCAL_CHAR_PATTERN =

Characters allowed in the local part without quoting (RFC 5322 dot-atom).

%r{\A[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+\z}
LABEL_PATTERN =

Pattern for a valid domain label.

/\A[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\z/

Class Method Summary collapse

Class Method Details

.valid?(email) ⇒ Boolean

Check if an email address has valid syntax.

Parameters:

  • email (String)

    the email address to check

Returns:

  • (Boolean)


64
65
66
# File 'lib/philiprehberger/email_validator/syntax.rb', line 64

def valid?(email)
  validate(email).empty?
end

.validate(email) ⇒ Array<String>

Validate the syntax of an email address.

Parameters:

  • email (String)

    the email address to validate

Returns:

  • (Array<String>)

    list of error messages (empty if valid)



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/philiprehberger/email_validator/syntax.rb', line 33

def validate(email)
  errors = []

  return ['email must be a string'] unless email.is_a?(String)

  stripped = email.strip

  return ['email must not be empty'] if stripped.empty?

  if stripped.length > MAX_EMAIL_LENGTH
    errors << "email exceeds maximum length of #{MAX_EMAIL_LENGTH} characters"
  end

  parts = stripped.split('@', -1)

  return ['email must contain an @ symbol'] if parts.length < 2

  return ['email must contain exactly one @ symbol'] if parts.length > 2

  local, domain = parts

  errors.concat(validate_local(local))
  errors.concat(validate_domain(domain))

  errors
end