Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - REGEX for email validation

Tags:

I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end

Problem with the above is [email protected] does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

like image 743
AnApprentice Avatar asked Jan 22 '11 19:01

AnApprentice


People also ask

How to validate email format in Rails?

Email_validator gem validation For example, a simple one to use is the email_validator gem. It's that simple! This gem provides a simple email validation technique by checking if there's an at-sign (@) with some characters before or after it. If the sign is present, it returns, true; otherwise, it returns false.

How to validate email in Ruby?

The first validation method, validates_presence_of, checks whether the email field is empty. The second method, validates_format_of, compares the email with the particular regular expression. The advantage here is that the same regular expression can be used to validate emails in different classes and methods.


2 Answers

validates_format_of :email, 
  :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i

Don't ask me to explain it! That was from a validation plugin that I've since lost track of as all I needed was the email regex.

like image 86
scragz Avatar answered Sep 16 '22 15:09

scragz


Not enough reputation to add a comment but if you are going to use the Devise regexp, and you are already using Devise itself, then you can simply use:

validates :email, presence: true, format: Devise.email_regexp

like image 23
apanzerj Avatar answered Sep 19 '22 15:09

apanzerj