I have a User model in a Rails application which has an email field. Is there a default validation that will ensure the email is in the correct format? If not, how would I go about validating that field?
            Asked
            
        
        
            Active
            
        
            Viewed 3.0k times
        
    41
            
            
        - 
                    by `valid email address` do you mean the email really exists, or it fits email format? – nurettin Dec 09 '12 at 06:55
- 
                    12It's odd that this was closed. It may not be terribly specific, but I see a real question here. – sscirrus May 23 '13 at 19:11
- 
                    @sscirrus Well, to be totally knit-picky, he didn't actually ask a question. Also, it's not good conduct to just ask for code handouts on SO. A more appropriate question would be "how would one go about writing code that does [desired outcome]?" – Michael Dorst Jun 23 '13 at 05:38
- 
                    @MichaelDorst Fair point - while I do see a question in the text, I agree with you that SO isn't for code handouts. – sscirrus Jun 24 '13 at 18:34
- 
                    @sscirrus As I said, I'm being knit-picky, but the OP simply **stated** what he was looking for, he did not **ask** a question. You may be able to **infer** a question from that statement, but the OP did not explicitly ask anything - hence: `closed as not a real question`. I agree with the five people who chose to do that because I feel that ill-formed questions can only lead to ill-formed answers, neither of which are helpful to this community. – Michael Dorst Jun 24 '13 at 22:50
- 
                    I follow this post: http://stackoverflow.com/questions/4776907/what-is-the-best-easy-way-to-validate-an-email-address-in-ruby. I tested article post: http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/ by Ruby 2.1.0 and Rails 4.0.3 hosted into Heroku. – d.danailov Apr 07 '14 at 09:12
- 
                    Here is the new way to do it: `validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }` – Cyzanfar Oct 11 '17 at 21:10
1 Answers
97
            Add in your gemfile:
gem 'validates_email_format_of'
and in your model:
validates :email, email_format: { message: "doesn't look like an email address" }
Or if you don't want use a gem, use regex:
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
 
    
    
        Chris Cashwell
        
- 22,308
- 13
- 63
- 94
 
    
    
        Jonathan Vukovich-Tribouharet
        
- 1,978
- 14
- 17
- 
                    1
- 
                    1Use just: `with: /@/` https://davidcel.is/posts/stop-validating-email-addresses-with-regex/ – Bruno Casali May 27 '16 at 17:59
 
    