What is the best/easy way to validate an email address in ruby (on the server side)?
-
1What do you mean by "validate"? Guaranteed not syntactically invalid? Tested to have an existing domain? Found to exist and respond? – Phrogz Jan 23 '11 at 22:16
-
1possible duplicate of [What's the best way to validate multiple emails and handle errors in Rails?](http://stackoverflow.com/questions/675271/whats-the-best-way-to-validate-multiple-emails-and-handle-errors-in-rails) – Phrogz Jan 23 '11 at 22:17
-
possible duplicate of [How can I validate multiple email addresses in a model?](http://stackoverflow.com/questions/1255116/how-can-i-validate-multiple-email-addresses-in-a-model) – Nakilon Jan 23 '11 at 22:18
-
See also [What's the state of the art in email validation for rails?](http://stackoverflow.com/questions/1156601/whats-the-state-of-the-art-in-email-validation-for-rails) – Phrogz Jan 23 '11 at 22:22
-
@fabspro rather than deriding the OP, can you explain what's wrong with David Sulc's answer? – Andrew Grimm Apr 04 '13 at 21:53
-
@AndrewGrimm For starters, the question is a ruby language question but the accepted answer is a ruby on rails framework answer. Then as you can see, in the comments thread, people asked for clarification as to what the asker means by validation (check syntax against rfc standard, test if the domain exists, check if the email address works), and these requests were ignored. Also, the question was asked despite three duplicates being linked in this comments thread alone. Then he selects an answer at random, awarding rep for a person giving a "wild shot" answer hoping to meet the asker's whims. – fabspro Apr 12 '13 at 03:37
-
@fabspro the question was tagged with Rails, and talks about "on the server side", so a Rails answer should be ok. – Andrew Grimm Apr 12 '13 at 03:53
-
@AndrewGrimm The asker has asked a question which has been asked /many/ times on this website and others, and asked the question in such a broad way that a specific answer was impossible. Despite this, he chose to pick an answer based on his own feelings instead of choosing the answer that best reflects upon the question. For example, why was David Sulc's answer chosen instead of paxdiablo's? The asker treats SO as his own personal google, and wastes the time of every community member who tries to actually answer questions. You are encouraging this poor attitude and are part of the problem. – fabspro Apr 12 '13 at 05:36
-
Use https://github.com/OpenGems/rails_email_checker – Boris BRESCIANI Feb 16 '20 at 08:33
10 Answers
You could look whether or not it matches a regexp like the one used in this Rails validator:
validates_format_of :email,:with => /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
But if you use Devise, simply do:
validates_format_of :email,:with => Devise::email_regexp
Source: http://lindsaar.net/2008/4/14/tip-4-detecting-a-valid-email-address
Edit 1:
useful website for tests: http://www.rubular.com/

- 114,565
- 26
- 219
- 213
-
-
1
-
-
@ArtemKalinchuk thanks for your comment! I've updated, actually I now rely on Devise regexp to reamin DRY – apneadiving Aug 16 '13 at 15:28
-
3While I consider the answer as good, I have to mention that ruby != rails. The answer does not provide a solution outside the ActiveRecord validations scope. – Matei Iorgulescu May 06 '16 at 15:32
-
-
As of Devise 4.2.0 the Devise::email_regexp doesn't catch scenarios like user@domain (without the .com) - it actually returns them as valid. I've switched away from using it because the regex example actually checks for the .com/TLD – kylekeesling Jan 12 '17 at 21:01
-
Regular Expressions add a false sense of correctness of email address validations and they can't implement RFC 5322 or a more future-proof RFC 3490. Just validate email address with confirmation email message as paxdiablo says, and fail delivering will tell if email address is probably wrong. If one insist in using regexp it should be only an extra step and it should be permissive. – Andre Figueiredo Jan 28 '19 at 03:17
In Ruby? The same way as in any language.
Send a confirmation email to the address with a link that the recipient has to click before the email address is considered fully validated.
There are any number of reasons why a perfectly formatted address may still be invalid (no actual user at that address, blocked by spam filters, and so on). The only way to know for sure is a successfully completed end-to-end transaction of some description.

- 854,327
- 234
- 1,573
- 1,953
-
3+1. A Regexp is a good "trivial rejection" technique, but not a complete solution. Sending a validation email in conjunction with Regexping seems relatively optimal. – EnabrenTane Jan 23 '11 at 22:22
-
1this is the best suggestion. make the input type=email so that it triggers basic flags. other than that just send a confirmation email. – Blair Anderson Oct 26 '18 at 17:17
validates :email, presence: true, format: /\w+@\w+\.{1}[a-zA-Z]{2,}/
checks that email field is not blank and that one or more characters are both preceding the '@' and following it
Added specificity, any 1 or more word characters before an the @
and any 1 or more word character after and in between specifically 1 .
and at least 2 letters after

- 302
- 2
- 12
I know that this is a old question but I was looking for a simple to way to do this. I came across a email_validator gem this is really simple to set up and use.
as a validator
validates :my_email_attribute, :email => true
Validation outside a model
EmailValidator.valid?('narf@example.com') # boolean
I hope that this help everyone.
Happy Codding

- 10,108
- 9
- 71
- 116
Shortcut Form:
validates :email, :format => /@/
Normal Form (Regex) :
validates :email, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/ }
Source: Validator Class

- 4,534
- 6
- 25
- 24
You can use
<%=email_field_tag 'to[]','' ,:placeholder=>"Type an email address",:pattern=>"^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$",:multiple => true%>

- 1,151
- 1
- 19
- 31
-
2Wouldn't you want to validate this in the controller or model. If the html does it, you could just send a http command and get around this check. – alex_milhouse Mar 04 '16 at 00:37
Since the main answer's blog site was down, here is the snippet of code from that site via nice cacher or gist:
# http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/
class EmailValidator < ActiveModel::EachValidator
# Domain must be present and have two or more parts.
def validate_each(record, attribute, value)
address = Mail::Address.new value
record.errors[attribute] << (options[:message] || 'is invalid') unless (address.address == value && address.domain && address.__send__(:tree).domain.dot_atom_text.elements.size > 1 rescue false)
end
end

- 1,618
- 1
- 14
- 22
You can take reference from https://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i

- 522
- 1
- 8
- 23
If you are using Rails/Devise - addition to @apneadiving`s answer -
validates_format_of :email,:with => Devise::email_regexp
Devise::email_regexp is taken from config/initializers/devise.rb
config.email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/

- 1,962
- 3
- 19
- 27
Send a confirmation mail , and I will usualy use this validator ... D.R.Y.
# lib/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
EmailAddress = begin
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
'\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
quoted_pair = '\\x5c[\\x00-\\x7f]'
domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
domain_ref = atom
sub_domain = "(?:#{domain_ref}|#{domain_literal})"
word = "(?:#{atom}|#{quoted_string})"
domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
local_part = "#{word}(?:\\x2e#{word})*"
addr_spec = "#{local_part}\\x40#{domain}"
pattern = /\A#{addr_spec}\z/
end
def validate_each(record, attribute, value)
unless value =~ EmailAddress
record.errors[attribute] << (options[:message] || "is not valid")
end
end
end
in your model
validates :email , :email => true
or
validates :email, :presence => true,
:length => {:minimum => 3, :maximum => 254},
:uniqueness => true,
:email => true

- 3,515
- 2
- 22
- 14
-
maybe not so easy , but you have to write it once and use everytime you need – andrea Jan 23 '11 at 22:35
-
4