Tuesday, 14 May 2013

Email domain validation in ruby

Hi,

Most of the web applications will have registration forms and every form will have email field as the mandatory. We use regular expression to validate the email format. But some times we may come across tio validate the given email id was valid or not that means does the domain exists or not.

Below is the useful code to validate the domain name in ruby with the help of MX records.


In email_validation.rb


require 'resolv'

class EmailValidation
def self.validate_email_domain(email)
domain = email.match(/\@(.+)/)[1]
Resolv::DNS.open do |dns|
@mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
end
puts @mx.size > 0 ? true : false
end
end


s = EmailValidation.validate_email_domain("umamaheshvarma@gmail.com")


The above method will return true if the domain exists.


Thank You,
Uma Mahesh

No comments:

Post a Comment