Skip to content

Instantly share code, notes, and snippets.

@dawidlenkiewicz
Created August 19, 2014 15:43

Revisions

  1. dawidlenkiewicz created this gist Aug 19, 2014.
    19 changes: 19 additions & 0 deletions email_validator.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    class EmailValidator < ActiveModel::EachValidator
    require 'resolv'

    def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
    record.errors[attribute] << (options[:message] || I18n.t('email.wrong'))
    end

    split_email = value.split("@")
    domain = split_email[1].to_s
    Resolv::DNS.open do |dns|
    @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
    end
    if @mx.blank?
    record.errors[attribute] << (options[:message] || I18n.t('email.wrong_domain'))
    end
    end

    end