Class: DeviseEmailValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/devise_email_validator.rb

Overview

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

Constant Summary collapse

DEFAULT_OPTIONS =
{
  regexp: Devise.email_regexp
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ DeviseEmailValidator

Returns a new instance of DeviseEmailValidator.

Raises:

  • (ArgumentError)

25
26
27
28
29
30
31
# File 'app/validators/devise_email_validator.rb', line 25

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

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object


33
34
35
# File 'app/validators/devise_email_validator.rb', line 33

def validate_each(record, attribute, value)
  record.errors.add(attribute, :invalid) unless value =~ options[:regexp]
end