How to Validate Email Using Ruby: Simple Guide and Examples
To validate an email in Ruby, use a
regular expression (regex) that matches the email pattern, or use the URI::MailTo::EMAIL_REGEXP constant for a built-in pattern. You can check if an email matches the pattern with =~ or match? methods.Syntax
Use a regular expression (regex) to check if the email string fits the common email format. The pattern usually checks for characters before and after an '@' symbol and a domain.
Example parts:
email =~ /pattern/: Returns the index of the match ornilif no match.email.match?(pattern): Returnstrueorfalseif the email matches the pattern.URI::MailTo::EMAIL_REGEXP: A built-in Ruby regex for email validation.
ruby
email = "user@example.com" pattern = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i if email =~ pattern puts "Valid email" else puts "Invalid email" end
Output
Valid email
Example
This example shows how to validate multiple emails using Ruby's built-in URI::MailTo::EMAIL_REGEXP. It prints whether each email is valid or invalid.
ruby
require 'uri' emails = [ "test@example.com", "invalid-email", "user.name+tag@domain.co", "user@.com", "user@domain" ] emails.each do |email| if email.match?(URI::MailTo::EMAIL_REGEXP) puts "#{email} is valid" else puts "#{email} is invalid" end end
Output
test@example.com is valid
invalid-email is invalid
user.name+tag@domain.co is valid
user@.com is invalid
user@domain is invalid
Common Pitfalls
Common mistakes when validating emails in Ruby include:
- Using too simple regex that allows invalid emails or blocks valid ones.
- Not anchoring the regex with
\Aand\z, which can cause partial matches. - Ignoring case sensitivity by not using the
iflag. - Assuming all valid emails follow the same pattern; some valid emails have unusual characters.
Always test your regex with various email examples.
ruby
email = "user@example.com extra" pattern_wrong = /[\w+\-.]+@[a-z\d\-.]+\.[a-z]+/i pattern_right = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i puts "Wrong pattern match? #{!!(email =~ pattern_wrong)}" puts "Right pattern match? #{!!(email =~ pattern_right)}"
Output
Wrong pattern match? true
Right pattern match? false
Quick Reference
Summary tips for email validation in Ruby:
- Use
URI::MailTo::EMAIL_REGEXPfor a reliable built-in pattern. - Always anchor your regex with
\Aand\zto avoid partial matches. - Use
match?for a simple true/false check. - Test with multiple email formats to ensure accuracy.
Key Takeaways
Use Ruby's built-in URI::MailTo::EMAIL_REGEXP for reliable email validation.
Anchor regex patterns with \A and \z to prevent partial matches.
Use match? method for simple true/false email checks.
Test your validation with various email formats to avoid errors.
Avoid overly simple regex that can allow invalid emails.