Sign up
development

How to Validate Email in Ruby on Rails

Angela Stringfellow

Last updated on

Email is one of the oldest methods for transmitting messages through the internet, yet the use of emails remains prevalent in this era of nifty messaging applications. Email acts as the gateway to all digital engagement with brands, and almost everyone has an email account. This makes it one of the most effective mediums for engaging, acquiring, converting, and retaining customers. The relevance of emails for marketing purposes continues to increase.

Email Validation

Email validation ensures that the email entered by the user is in line with email syntaxes. It can be used to make sure that the user has not made mistakes like typos that would invalidate the email. It determines whether a genuine email inbox is present for the validated email ID.

Importance of Valid Email

Almost half of all emails sent end up in the junk folder. Most of the time, email providers determine what emails end up in the junk folder. When you try to send mail to an invalid address, it bounces back to the server from which the mail originated. This becomes a black mark on the sender of the email. The higher the bounce rate, the lower the reputation of the sender.

ISPs and email service providers keep track of all such instances experienced by them. This data is then used to decide which emails are sent to the inbox and which emails will end up in junk. Weeding out invalid emails from a list decreases the bounce rate. These result in brownie points for the sender. Sending emails only to valid email IDs ensures that more recipients receive the emails in their inbox.

Email ID Syntax

Every email ID has three components: @ symbol, a prefix, and domain. The prefix appears to the left of the @ symbol, and the domain name is to the right of the symbol. Having an @ symbol is a must for an email ID to be valid. In addition to this, there are prescribed formats for prefixes and domains in an email ID.

Prefix format:

  • Letters, numbers, underscores, periods, and dashes can be characters of prefixes.
  • Underscores, periods, and dashes cannot appear at the end of prefixes. This means they must always be followed by at least one letter or number.
  • There cannot be two consecutive symbols (underscores, periods, or dashes).

Similarly, the domain also has a specified format:

  • Letters, numbers, periods, and dashes are the only characters allowed.
  • Periods are only used for separating the domain name from TLD (top level domain). Periods cannot be used anywhere else in the domain.
  • The last part of the domain after the period should be a valid TLD. A valid TLD should have at least two characters.

Email Validation With Ruby

Ruby on Rails, a language used for a variety of programming needs such as building notification systems, can be used for email validation using one of three methods:

  • Regex validation
  • Active records validation
  • Gems based validation

Regex Validation

Regex or regular expression can be used to develop patterns to identify and match texts. You can create a regex to check whether an entered email is in the format of email IDs.

A simple regex to check whether the entered text contains the @ symbol:

^(.+)@(.+)$

And a regex that checks for the complete requirement for email IDs is:

^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/
=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$

This can be used as part of a method to validate email IDs:

EMAIL_REGEX =^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$ 

def valid_email? email
  email =~EMAIL_REGEX
end

puts valid_email?("[email protected]") ? "Valid Email" ∶ "Invalid Email"

The output of the code given above will be Valid Email. If an email id without the proper syntax was given as the input, the result would have been Invalid Email.

Active Records Validation

In most cases, input fields of a form are injected into the ActiveRecord model. Active validation helpers are built-in with Ruby on Rails. They can be used to validate the states of objects before they are used in the program. You can define the rules of validation using the ActiveRecord::Validations API. Consider a form that has email as the only input:

class UserData < ActiveRecord
  validates_presence_of ∶email
  validates_format_of   ∶email, with: EMAIL_REGEX
end

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.

Gem Validation

Ruby Gems package manager has many gems that are suitable for validating emails. It’s easy to use and can be used in any program. One such gem is the email_validator developed by K&R software. The name of the package must be included in the Gemfile to use it. Add the following snippets to the Gemfile and run bundler:

gem 'email_validator'  

bundle install

The following code snippet can be used to validate email. By default, the email_validator package only checks if there is an @ symbol in the text and if there are characters before and after the symbol. You can provide additional characteristics to check if required. When used in a method, it returns true if the email is valid and false if the email is invalid. It can be used in the following manner:

class User < ActiveRecord::Base 
  validates ∶email_attributes,email: true
end

Using such gems makes the life of developers easier. More such gems can be found at the RubyGems website.

Validating email IDs before sending emails is essential to maintain the reputation of the mail server. This helps senders reach the inboxes of more customers or prospects. Ruby on Rails can be used to easily validate emails in the three ways outlined in this post.