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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With