Guides
Last updated
July 20, 2025

5 Ways to Implement Email Validation in Rails

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating email addresses in a Rails application helps maintain data quality and prevent user sign-up problems. We'll walk through five implementation methods with code snippets, look at the pitfalls of these traditional approaches, and see how Abstract API addresses their limitations.

How to Implement Email Validation in Rails

Here are four common ways to validate email addresses in a Rails application. Each method uses a different approach, from built-in constants and regular expressions to specialized gems.

Inline Regular Expression

This method uses pure ActiveModel format validation. The regular expression, or regex, can be adjusted for specific domains, such as to allow or disallow sub-domains. This approach keeps the dependency graph small because it requires no gem, DNS call, or extra allocations.

class User < ApplicationRecord
  EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: EMAIL_REGEX }
end

Built-in URI::MailTo::EMAIL_REGEXP

This constant is part of the Ruby standard library, which Rails uses automatically. The expression mirrors the WHATWG “type=email” browser check, so server-side and client-side validation share the same rules. It requires no gem and is simpler to audit than a complex, custom pattern.

class User < ApplicationRecord
  validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
end

The activemodel-email_address_validator Gem

This is a plug-and-play ActiveModel validator. It understands internationalization (i18n), rejects local-only addresses, and can perform a DNS lookup for Mail Exchange (MX) record presence. Custom rules can be stacked with a predicate or regex to enforce domain-specific policies, like company-only emails.

# Gemfile
gem 'activemodel-email_address_validator'

# Model
class User < ApplicationRecord
  validates :email, email_address: true                 # basic
  validates :email, email_address: { mx: true }          # DNS MX lookup
  validates :email, email_address: { with: /…/ }         # custom rule
end

The email_address Gem

This gem provides a full parser that tokenizes and normalizes email addresses. It can generate a canonical form, a redacted form, and offers ActiveRecord type casting. It supports strict, RFC, and loose validation modes.

The gem also autocorrects case, strips tags from addresses like user+tag@example.com, and can compare canonical forms for uniqueness. Its validator integrates with I18n for custom error messages.

# Gemfile
gem 'email_address'

# Model
class User < ApplicationRecord
  validates_with EmailAddress::ActiveRecordValidator, field: :email
end

Challenges of Email Validation in Rails

Traditional validation methods in Rails often fall short. They struggle with complex email standards, international addresses, and cannot confirm if an email is actually deliverable, which creates several problems for applications.

  • Simplified regexes, like URI::MailTo::EMAIL_REGEXP and custom patterns, do not fully comply with RFC-5322. They often reject valid addresses with edge cases like apostrophes or quoted parts, yet still permit some invalid formats to pass.
  • Most Rails patterns fail with internationalized mailboxes. ASCII-focused character classes in methods like inline regex reject valid Unicode local parts and international domain names. This approach blocks legitimate global users or forces them to use confusing punycode forms.
  • Syntax validation alone does not confirm deliverability. Methods from inline regex to the activemodel-email_address_validator gem cannot verify if a mailbox exists or accepts mail. A syntactically correct email can still bounce or land in a spam folder.
  • The email landscape constantly changes with new top-level domains and disposable providers. Hard-coded inline regex patterns quickly become outdated. This leads to the rejection of valid new emails and the acceptance of throwaway addresses without frequent manual updates.

Validate Emails with Abstract API
Ensure every email is valid in your Rails project for clean data and deliverability.
Get started for free

How Abstract API Handles Email Validation in Rails

Abstract API addresses the core weaknesses of traditional validation methods. It provides advanced typo detection, rapid server checks, and dynamic blocklist maintenance.

  • It adds ML-powered typo detection with autocorrect suggestions. This catches common mistakes like john@gmial.com that simple regex validation misses.
  • The API performs fast MX and real-time SMTP handshakes. It reports if an address is DELIVERABLE, UNDELIVERABLE, or UNKNOWN, which avoids slow checks that block threads on your server.
  • It removes the need for manual blocklist upkeep. The service refreshes its database of over 3,000 disposable domains, flags role-based addresses, and assigns a quality score so you can adjust acceptance rules.

How to Add Abstract API to Your Dev Environment

Once you know Abstract’s capabilities, you can add its email validation API to your project with ease. Follow these steps to prepare your development environment.

  • Add an HTTP client, like Faraday, to your Gemfile.
  • Execute bundle install from your terminal.
  • Sign up at Abstract, create an Email Validation key, and copy it.
  • Store the key inside Rails credentials or as an environment variable.
  • Create the service file app/services/abstract_email_validator.rb with the code below.
class AbstractEmailValidator
  ENDPOINT = 'https://emailvalidation.abstractapi.com/v1/'.freeze

  def self.validate(email)
    res = Faraday.get(ENDPOINT, { api_key: ENV.fetch('ABSTRACT_EMAIL_API_KEY'), email: email }, { 'Accept' => 'application/json' })
    JSON.parse(res.body, symbolize_names: true)
  end
end

Sample Email Validation Implementation with Abstract API

The code below adds a custom validation method to a Rails model. This method calls the service you created. It checks the deliverability and disposable email status from the API response.

If the email is not deliverable or comes from a disposable domain, the method adds an error to the model.

validate :email_must_be_deliverable

def email_must_be_deliverable
  r = AbstractEmailValidator.validate(email)
  unless r[:deliverability] == 'DELIVERABLE' && !r[:is_disposable_email][:value]
    errors.add(:email, 'cannot be delivered')
  end
end

The API returns a clear JSON response that you can cache or log. Here is a sample of the data you receive.

{
 "email":"eric@abstractapi.com",
 "deliverability":"DELIVERABLE",
 "quality_score":"0.80",
 "is_valid_format":{"value":true},
 "is_free_email":{"value":false},
 "is_disposable_email":{"value":false},
 "is_role_email":{"value":false},
 "is_catchall_email":{"value":true},
 "is_mx_found":{"value":true},
 "is_smtp_valid":{"value":true}
}

The response provides a complete picture of email quality. The deliverability field summarizes all checks. The quality_score lets you weigh borderline results. Boolean flags like is_disposable_email expose specific risks, so you can build a custom validation policy.

Final Thoughts

Traditional validation methods often fail. They miss typos, slow your servers with DNS checks, and require constant blocklist updates. Abstract API solves these issues with a single API call. It provides typo correction, fast server checks, and dynamic blocklists. To reliably validate user emails, consider a free account on Abstract API to get your API key.

Validate Emails with Abstract API
Start validating emails in your Rails application to protect your data and boost email deliverability.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required