Created
April 22, 2012 21:55
-
-
Save Nucc/2467163 to your computer and use it in GitHub Desktop.
Email validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'resolv' | |
class EmailValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless value =~ /\A([^@\s]+)@([^.\s]+)\..+\z/i and valid_mx_record?(value) | |
record.errors[attribute] << (options[:message] || "is not an email") | |
end | |
end | |
private | |
def valid_mx_record?(email) | |
domain = email.match(/\@(.+)/)[1] | |
Resolv::DNS.open do |dns| | |
@mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) | |
end | |
@mx.size > 0 ? true : false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment