Site icon Mailtrap

How to Validate Email Format in Rails: Regex and Gems

Validating emails in Ruby on Rails is important in increasing delivery rates, building the reputation of the sender, and enhancing conversion rates. Without undertaking validation, inaccurate and dead-end emails can fill up your application and make it difficult to send messages to your customers. 

Fortunately, Ruby on Rails provides several techniques for validating emails and improving their deliverability. Ultimately, the method you choose will depend on your preferences and extent of skills in Ruby programming. 

In this article, we’ll explain different methods for performing email validation in Rails and improving the capabilities of your messaging. 

How to Validate Email Format in Rails: Regex and Gems

Typically, a valid email address consists of the following three main sections: 

If this format is not adhered to, then the email address could become invalid. The formal definitions of the required format are contained in RFC 5322 and RFC 5321 documents.

In most cases, the local section of an email address may use any of these ASCII standard characters:

Also, the domain name part may use these characters:

For example, while an email address like alice.bob@example.com would be valid, if it does not have the @ character, it would be invalid. 

Rails Email Validation Techniques

As earlier mentioned, there are several techniques for validating email addresses in Ruby on Rails.

In this article, we’ll talk about these four:

Let’s look at each of them.

Regex validation

A regular expression, usually shortened to regex, refers to a sequence of characters that lets you develop patterns for matching, locating, and managing texts. You can use regex to check if the format for the provided email address is valid or not. 

You can create any type of regex to validate email formats. For example, here is a simple regex pattern that checks if an email address has the ‘@’ symbol. In this case, the other conditions for a valid email address will not be considered. 

^(.+)@(.+)$

Let’s see how it can be implemented in a Ruby program: 

REGEX_PATTERN = /^(.+)@(.+)$/ 
def is_email_valid? email
    email =~ REGEX_PATTERN
end
puts is_email_valid?("alice.bob@example.com") ? "Email valid" : "Email invalid"

As you can see in the code above, we created a function that uses the regex pattern to determine if the provided email address is valid.

If the code is run, it’ll output Email valid, indicating that the provided email address is in the required syntax. 

Next, let’s improve the regex pattern by adding some limitations to be applied to the local and domain sections. 

These are the limitations we want to apply:

This is the regex pattern:

^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$

Let’s see how it can be implemented in a Ruby program: 

REGEX_PATTERN = /^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$/ 
def is_email_valid? email
    email =~ REGEX_PATTERN
end
puts is_email_valid?("alice#@example.com") ? "Email valid" : "Email invalid"

If the code above is run, it’ll output Email invalid, indicating that the provided email address is not in the required syntax. 

Lastly, let’s improve the regex pattern by adding a limitation to the domain name section.

These are the limitations we want to apply:

This is the regex pattern:

^[A-Za-z0-9+_.-]+@([A-Za-z0-9]+\.)+[A-Za-z]{2,6}$

Let’s see how it can be implemented in a Ruby email validation regex program: 

REGEX_PATTERN = /^[A-Za-z0-9+_.-]+@([A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/
def is_email_valid? email
    email =~ REGEX_PATTERN
end
puts is_email_valid?("alice@example.c") ? "Email valid" : "Email invalid"

If the code above is run, it’ll output Email invalid, indicating that the provided email address is not in the required syntax. 

Active Record validations

An exciting thing about Ruby on Rails is that it provides built-in Active Record validation helpers that allow you to validate the state of objects before they’re processed. You can use them to create your own email validation methods and display error messages to users.

For example, you can use the format helper to check if an email address matches the provided regex pattern, which is defined using the :with option. 

Let’s see how you can add the helper to your model:

class User < ApplicationRecord  validates :email, 
	  format: { with: /\A(.+)@(.+)\z/, message: "Email invalid"  }, 
            uniqueness: { case_sensitive: false }, 
            length: { minimum: 4, maximum: 254 }          
end

As you can see on the above code, if the Active Record has carried out the validation, and the email address is invalid, the error message specified using the :message option will be displayed to the user. Note that we specified the regex pattern used earlier in this article.

Also, we added the uniqueness and the length helpers to confirm the uniqueness and the length of the provided email address, respectively. 

Email_validator gem validation

There are several Ruby gems you can use to validate email addresses. For example, a simple one to use is the email_validator gem. 

To start using this gem, add the following to your Gemfile:

gem 'email_validator'

Next, run the Bundler to install it:

bundle install

Then, here is how you can add it to your model:

class User < ActiveRecord::Base
  validates :my_email_attribute, email: true	         
end

It’s that simple!

This gem provides a simple email validation technique by checking if there’s an at-sign (@) with some characters before or after it. If the sign is present, it returns, true; otherwise, it returns false

Providing such simple email validation avoids the risk of rejecting an email address that may seem to have strange characters, but is in fact valid. It also saves you the hassle of looking for the perfect regex pattern to validate email addresses. 

Truemail gem validation

Truemail is another gem you can use to validate email addresses. It provides more validation features than the email_validator gem.

With the Truemail Ruby gem, you can check the validity of an email address via regex, SMTP, or DNS. In this article, we’ll show how to use it to verify emails via a regex pattern. 

To start using this gem, add the following to your Gemfile:

gem 'truemail'

Next, run the Bundler to execute it:

bundle install

You’ll also need to configure it according to the instructions given in its documentation. The minimum configuration required for Truemail to run is to specify the verifier email that will be used. You can do this by creating a file in config/initializers/ directory, named truemail.rb

Truemail.configure do |config|
  config.verifier_email = 'verifier@yourdomain.com'
end

Then, here is how you can use it to validate email addresses:

Truemail.validate('alicebob@example.com', with: :regex)

=> #<Truemail::Validator:0x000055590cc9bdb8
  @result=
    #<struct Truemail::Validator::Result
      success=true, email="alicebob@example.com",
      domain=nil,
      mail_servers=[],
      errors={},
      smtp_debug=nil>,
  @validation_type=:regex>

You can also use the .valid? helper method, which is a shortcut for the validate method, to validate email addresses quickly. The helper returns a boolean and not a whole validation object.

Here is an example:

Truemail.valid?('alicebob@example.com', with: :regex)


=> true

Note that Truemail comes with a default regex pattern for validating email addresses. So, you can provide your own regex to override its default pattern. 

Conclusion

Validating email formats is a challenging thing. However, if you get it right, sending emails with Ruby will lead to the expected outcomes. Additionally, you can run email tests in a safe environment such as Mailtrap Email Testing. It’s an Email Sandbox that captures outgoing SMTP traffic, thus preventing spamming recipients and allowing developers to inspect and debug emails.


By using Email Testing, you can get quick access to email’s metadata, review and validate its HTML, run a spam analysis, and much more.

We hope that this article will assist you in starting to implement email validation in your Ruby applications and take their capabilities to the next level.

If you find this article useful, please share it with your friends. We (and them) will really appreciate it.

Happy sending emails! 

Exit mobile version