ruby
22 lines · 7 steps
Writing a custom email validator in Rails
A reusable ActiveModel validator that checks email format and enforces RFC length and dot rules.
Explained by
highlit
1class EmailValidator < ActiveModel::EachValidator
2 EMAIL_FORMAT = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\z/i
3
4 def validate_each(record, attribute, value)
5 return if value.blank?
6
7 normalized = value.to_s.strip.downcase
8
9 unless normalized.match?(EMAIL_FORMAT)
10 record.errors.add(attribute, options[:message] || :invalid)
11 return
12 end
13
14 local, domain = normalized.split("@", 2)
15
16 if local.length > 64 || normalized.length > 254
17 record.errors.add(attribute, :too_long)
18 elsif domain.include?("..") || local.start_with?(".") || local.end_with?(".")
19 record.errors.add(attribute, :invalid)
20 end
21 end
22end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Subclassing EachValidator lets you drop custom rules into any model with a one-line declaration.
- 2Normalizing input before validating avoids false failures from casing and stray whitespace.
- 3Regex handles shape while explicit length and dot checks catch cases a pattern misses.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/writing-a-custom-email-validator-in-rails-explained-ruby-7fa7/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.