Class: EmailValidator

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

Overview

EmailValidator class

Defined Under Namespace

Classes: Error

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



22
23
24
# File 'lib/email_validator.rb', line 22

def default_options
  @@default_options
end

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

Returns:

  • (Boolean)


35
36
37
# File 'lib/email_validator.rb', line 35

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


42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/email_validator.rb', line 42

def regexp(options = {})
  options = parse_options(options)
  case options[:mode]
  when :loose
    loose_regexp(options)
  when :rfc
    rfc_regexp(options)
  when :strict
    options[:require_fqdn] = true
    strict_regexp(options)
  else
    fail EmailValidator::Error, "Validation mode '#{options[:mode]}' is not supported by EmailValidator"
  end
end

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

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
# File 'lib/email_validator.rb', line 26

def valid?(value, options = {})
  options = parse_options(options)
  return true if value.nil? && options[:allow_nil] == true
  return false if value.nil?
  # quickly fail if domain is required but doesn't match
  return false unless options[:domain].nil? || value[/^.*@#{regexp_safe_domain(options)}$/]
  !!(value =~ regexp(options))
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



161
162
163
164
# File 'lib/email_validator.rb', line 161

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