Sha256: 68b21153189f12523729093806f9b8182789efba08a3db78ed699015f79df0b1

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

require "valid_email2/address"
require "active_model"
require "active_model/validations"

module ValidEmail2
  class EmailValidator < ActiveModel::EachValidator
    def default_options
      { regex: true, disposable: false, mx: false, strict_mx: false, disallow_subaddressing: false, multiple: false }
    end

    def validate_each(record, attribute, value)
      return unless value.present?
      options = default_options.merge(self.options)

      value_spitted = options[:multiple] ? value.split(',').map(&:strip) : [value]
      addresses = value_spitted.map { |v| ValidEmail2::Address.new(v) }

      error(record, attribute) && return unless addresses.all?(&:valid?)

      if options[:disallow_dotted]
        error(record, attribute) && return if addresses.any?(&:dotted?)
      end

      if options[:disallow_subaddressing]
        error(record, attribute) && return if addresses.any?(&:subaddressed?)
      end

      if options[:disposable]
        error(record, attribute) && return if addresses.any?(&:disposable?)
      end

      if options[:disposable_domain]
        error(record, attribute) && return if addresses.any?(&:disposable_domain?)
      end

      if options[:disposable_with_whitelist]
        error(record, attribute) && return if addresses.any? { |address| address.disposable? && !address.whitelisted? }
      end

      if options[:disposable_domain_with_whitelist]
        error(record, attribute) && return if addresses.any? { |address| address.disposable_domain? && !address.whitelisted? }
      end

      if options[:blacklist]
        error(record, attribute) && return if addresses.any?(&:blacklisted?)
      end

      if options[:mx]
        error(record, attribute) && return unless addresses.all?(&:valid_mx?)
      end

      if options[:strict_mx]
        error(record, attribute) && return unless addresses.all?(&:valid_strict_mx?)
      end
    end

    def error(record, attribute)
      record.errors.add(attribute, options[:message] || :invalid)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
valid_email2-3.6.1 lib/valid_email2/email_validator.rb
valid_email2-3.6.0 lib/valid_email2/email_validator.rb