Class: EmailValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/email_validator.rb

Overview

Constant Summary collapse

@@default_options =

rubocop:disable Style/ClassVars

{
  :allow_nil => false,
  :domain => nil,
  :require_fqdn => nil,
  :mode => :loose
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_optionsObject



13
14
15
# File 'lib/email_validator.rb', line 13

def default_options
  @@default_options
end

.invalid?(value, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/email_validator.rb', line 24

def invalid?(value, options = {})
  !valid?(value, options)
end

.regexp(options = {}) ⇒ Object

Refs:

https://tools.ietf.org/html/rfc2822 : 3.2. Lexical Tokens, 3.4.1. Addr-spec specification
https://tools.ietf.org/html/rfc5321 : 4.1.2.  Command Argument Syntax


31
32
33
34
35
36
37
38
# File 'lib/email_validator.rb', line 31

def regexp(options = {})
  options = parse_options(options)
  if options[:mode] == :loose
    return /\A[^\s]+@[^\s]+\z/ if options[:domain].nil?
    return /\A[^\s]+@#{domain_pattern(options)}\z/
  end
  /\A(?>#{local_part_pattern})@#{domain_pattern(options)}\z/i
end

.valid?(value, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
# File 'lib/email_validator.rb', line 17

def valid?(value, options = {})
  options = parse_options(options)
  return true if value.nil? && options[:allow_nil] == true
  return false if value.nil?
  !!(value =~ regexp(options))
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



97
98
99
100
# File 'lib/email_validator.rb', line 97

def validate_each(record, attribute, value)
  options = @@default_options.merge(self.options)
  record.errors.add(attribute, options[:message] || :invalid) unless self.class.valid?(value, options)
end