Reputation: 696
I need to validate the email I tried the below expression
(/\b[A-Z0-9._%a-z-]+@(?:[A-Z0-9a-z-]+.)+[A-Za-z]{2,4}\z/)
But if some one giving email like [email protected]@domain1.com by mistake it takes this also a valid email. Please help me to get the exact regular expression for email in ruby.
Thanks in advance.
Upvotes: 2
Views: 4918
Reputation: 1451
You can use the built in ruby's email regexp URI::MailTo::EMAIL_REGEXP
Just add the
validates_format_of :user_email, with: URI::MailTo::EMAIL_REGEXP
in the model
Also, you can enhance the regexp using a different one, see @Daniel suggestion.
Upvotes: 3
Reputation: 15393
So you want to check if a particular string is a valid email address or not in Ruby.
You want to start by creating a constant variable that stores your regular expression.
There are countless resources with Regex cheat sheets that you can incorporate for matchers.
Here is the regular expression code that will verify that a string matches the common pattern followed by email addresses.
VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
If you look at this expression, the first part allows names, numbers, dashes and dots. This is followed by ensuring the @
symbol is used. And lastly this is followed by a a
and letters. This is typically in the format [email protected]
. At the end we are ensuring that the matcher is case insensitive with /i
.
To build a method that verifies this pattern
def is_valid_email? email
email =~ VALID_EMAIL_REGEX
end
The above method is called is_valid_email?
and we are passing it an argument called email
.
Next, we are checking this parameter against the VALID_EMAIL_REGEX
constant to return true
of false
. Then you can check some use cases:
p is_valid_email?("[email protected]") ? "Valid" : "Invalid"
p is_valid_email?("jonkinney.com") ? "Valid" : "Invalid"
p is_valid_email?("[email protected]") ? "Valid" : "Invalid"
p is_valid_email?("jon@kinney") ? "Valid" : "Invalid"
Executing this code should output:
"Valid"
"Invalid"
"Valid"
"Invalid"
The first and third email addresses are valid because they match the pattern, while the second and fourth are invalid.
Don't forget to enclose the arguments in your ternary operator in parentheses.
Upvotes: 1
Reputation: 4925
You can use the mail gem to parse any string according to RFC2822 like so:
def valid_email( value )
begin
value return false if value == ''
parsed = Mail::Address.new( value )
return parsed.address == value && parsed.local != parsed.address
rescue Mail::Field::ParseError
return false
end
end
This checks if the email is provided, i.e. returns false
for an empty address and also checks that the address contains a domain.
The mail gem is already included in Rails, so you can use the code above anywhere in your application.
Upvotes: 3