Skip to content

Instantly share code, notes, and snippets.

@superscott
Last active August 29, 2015 13:57
Show Gist options
  • Save superscott/9627914 to your computer and use it in GitHub Desktop.
Save superscott/9627914 to your computer and use it in GitHub Desktop.
rails email validator?
class Main
validate :email_is_valid
def email_is_valid
vtools = Tools.new
unless vtools.email_valid?(self.email)
logger.error("Invalid Email Domain :: PID: #{$$} EmailDomain: '#{vtools.domain}' ::")
errors.add(:base, "Invalid Email Address.")
end
end
end
class Tools
attr_reader :domain, :is_domain_registered, :is_domain_operational
def email_valid?(email_string)
email = Mail::Address.new(email_string)
email.domain.present? && domain_valid?(email.domain)
end
def domain_valid?(domain)
@domain = domain
@is_domain_registered = domain_registered?
@is_domain_operational = domain_operational?
@is_domain_registered || @is_domain_operational
end
private
def domain_registered?
begin
lookup = Whois.whois(@domain)
lookup.registered?
rescue Whois::ServerNotFound
false
end
end
def domain_operational?
begin
true if Resolv.getaddress(@domain)
rescue Resolv::ResolvError
false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment