Skip to content

Instantly share code, notes, and snippets.

@JamesFerguson
Forked from jcf/email_validator.rb
Created November 4, 2011 00:34
Show Gist options
  • Save JamesFerguson/1338367 to your computer and use it in GitHub Desktop.
Save JamesFerguson/1338367 to your computer and use it in GitHub Desktop.
Rails 3 Email Validator
require 'mail'
class EmailValidator < ActiveModel::EachValidator
attr_reader :record, :attribute, :value, :email, :tree
def validate_each(record, attribute, value)
@record, @attribute, @value = record, attribute, value
@email = Mail::Address.new(value)
@tree = email.__send__(:tree)
add_error unless valid?
rescue Mail::Field::ParseError
add_error
end
private
def valid?
!!(domain_and_address_present? && domain_has_more_than_one_atom?)
end
def domain_and_address_present?
email.domain && email.address == value
end
def domain_has_more_than_one_atom?
tree.domain.dot_atom_text.elements.length > 1
end
def add_error
if message = options[:message]
record.errors[attribute] << message
else
record.errors.add(attribute, :invalid)
end
end
end
require 'spec_helper'
VALID_RECOMMENDATION_ATTRS = {
:first_name => "John",
:recipient_email => "[email protected]"
}
describe EmailValidator do
subject { Recommendation.make_unsaved(VALID_RECOMMENDATION_ATTRS) } # assumes Machinist
%w[[email protected] [email protected] [email protected] [email protected]].each do |good_email|
it { should allow_value(good_email).for(:recipient_email) } # assumes shoulda-matchers
end
(%w[haxors @blah can@haz] + ['[email protected], [email protected]']).each do |bad_email|
it { should_not allow_value(bad_email).for(:recipient_email) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment