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 ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
ruby
require 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
php
<?php namespace App\Experiments;
Weighted random selection in PHP
weighted-random
cumulative-sum
sampling
Intermediate
8 steps
go
package events import ( "net/http"
Two-pass JSON dispatch in Gin
polymorphic-json
request-binding
validation
Intermediate
8 steps
ruby
class HashDiff Change = Struct.new(:from, :to) def self.call(before, after)
Diffing two hashes in Ruby
set-operations
struct
enumerable
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.