File: devise_email_validator.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (45 lines) | stat: -rw-r--r-- 1,413 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

# DeviseEmailValidator
#
# Custom validator for email formats. It asserts that there are no
# @ symbols or whitespaces in either the localpart or the domain, and that
# there is a single @ symbol separating the localpart and the domain.
#
# The available options are:
# - regexp: Email regular expression used to validate email formats as instance of Regexp class.
#           If provided value has different type then a new Rexexp class instance is created using the value.
#           Default: +Devise.email_regexp+
#
# Example:
#   class User < ActiveRecord::Base
#     validates :personal_email, devise_email: true
#
#     validates :public_email, devise_email: { regexp: Devise.email_regexp }
#   end
class DeviseEmailValidator < ActiveModel::EachValidator
  DEFAULT_OPTIONS = {
    regexp: Devise.email_regexp,
    encoded_word_regexp: %r{=[?].*[?]=}
  }.freeze

  def initialize(options)
    options.reverse_merge!(DEFAULT_OPTIONS)

    raise ArgumentError, "Expected 'regexp' argument of type class Regexp" unless options[:regexp].is_a?(Regexp)

    super(options)
  end

  def validate_each(record, attribute, value)
    return if record.errors.include?(attribute)

    record.errors.add(attribute, :invalid) unless valid_email?(value)
  end

  private

  def valid_email?(value)
    options[:regexp].match?(value) && !options[:encoded_word_regexp].match?(value)
  end
end