Module: ValidatesEmailFormatOf::Validations

Included in:
ActiveRecord::Base
Defined in:
lib/validates_email_format_of.rb

Instance Method Summary collapse

Instance Method Details

#validates_email_format_of(*attr_names) ⇒ Object

Validates whether the value of the specified attribute is a valid email address

class User < ActiveRecord::Base
  validates_email_format_of :email, :on => :create
end

Configuration options:

  • message - A custom error message (default is: “does not appear to be valid”)

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • allow_nil - Allow nil values (default is false)

  • allow_blank - Allow blank values (default is false)

  • check_mx - Check for MX records (default is false)

  • mx_message - A custom error message when an MX record validation fails (default is: “is not routable.”)

  • if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

  • unless - See :if



152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/validates_email_format_of.rb', line 152

def validates_email_format_of(*attr_names)
  options = { :on => :save,
    :allow_nil => false,
    :allow_blank => false }
  options.update(attr_names.pop) if attr_names.last.is_a?(Hash)

  validates_each(attr_names, options) do |record, attr_name, value|
    v = value.to_s
    errors = ValidatesEmailFormatOf::validate_email_format(v, options)
    errors.each do |error|
      record.errors.add(attr_name, error)
    end unless errors.nil?
  end
end