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 something@domain.extension
. 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?("jon@kinney.com") ? "Valid" : "Invalid"
p is_valid_email?("jonkinney.com") ? "Valid" : "Invalid"
p is_valid_email?("jon.k@kinney.com") ? "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.