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
class PurgeStaleExportsJob < ApplicationJob queue_as :maintenance retry_on ActiveRecord::Deadlocked, wait: :polynomially_longer, attempts: 5
Purging stale exports with an Active Job in Rails
background-jobs
batching
error-handling
Intermediate
7 steps
php
<?php namespace App\Http\Controllers\Auth;
Rate-limited login in Laravel
authentication
rate-limiting
validation
Intermediate
9 steps
javascript
function validateSignup({ email, password, confirmPassword, username, age }) { const errors = {}; if (!email) {
Building a signup validator in JavaScript
validation
regex
guard-clauses
Beginner
7 steps
javascript
const { validationResult, matchedData } = require('express-validator'); function validate(schema) { const runners = schema.map((rule) => rule.run.bind(rule));
A reusable validation middleware in Express
middleware
validation
higher-order-functions
Intermediate
8 steps
python
import re _UNIT_SECONDS = { "w": 604800,
Parsing duration strings like 1h30m in Python
regex
parsing
validation
Intermediate
8 steps
ruby
class ConfigFlattener def initialize(config) @config = config end
Flattening nested config into dotted keys
recursion
hashes
tree-traversal
Intermediate
8 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.