ruby-on-railsregexvalidationemail

Validate an Email with a Regex expression in Rails


See, I have the below simple regexp to validate an Email value.

^(|(([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})$

and when I run the same, it works! http://rubular.com/r/O3EDkx5a8t

See, I have an Excel file which contains Name, Email columns. While importing I need to validate Email id's, otherwise skip those rows from importing. I've done importing and all except this validation.

Now if I have the Email value in row["Email"] variable, suppose 'abc@gmail.com' How can I validate and confirm that the Emails are properly formatted?

I've seen match, scan methods for string matching using Regex. But, I'm not aware how to fit those in this context. When validating it should return true if it is a proper email, other wise it should return false. Please help :)


Solution

  • Yes, I found the answer:

    2.0.0-p247 :022 > "%_@gmail.com" =~ /^(|(([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})$/
     => nil 
    2.0.0-p247 :023 > "a@gmail.com" =~ /^(|(([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})$/
     => 0 
    

    When Email is proper, it will return 0, otherwise nil.