Skip to content

Instantly share code, notes, and snippets.

@Nucc
Created April 22, 2012 21:55
Show Gist options
  • Save Nucc/2467163 to your computer and use it in GitHub Desktop.
Save Nucc/2467163 to your computer and use it in GitHub Desktop.
Email validator
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