Integrations
Validate phone numbers and emails in Rails
Add Rails validators that check emails and phone numbers with Net::HTTP. Show errors on the model, store E.164 and fail open when the API is unavailable.
Updated 2026-11-23
This recipe adds email and phone validation to an Active Record model. Errors show on the form field, the normalized number is stored, and an API outage never blocks registration.
What you need
- Rails 7 or later on Ruby 3.0 or later.
net/httpships with Ruby. - A Qelka API key in
ENV['API_KEY']. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. A client in app/services
Save as app/services/qelka.rb:
require 'json'
require 'net/http'
module Qelka
BASE_URL = 'https://api.qelka.com/v1'.freeze
RETRYABLE = [429, 500, 502, 503].freeze
def self.call(path, body, max_attempts: 3)
uri = URI("#{BASE_URL}#{path}")
(1..max_attempts).each do |attempt|
request = Net::HTTP::Post.new(uri, 'Authorization' => "Bearer #{ENV.fetch('API_KEY')}", 'Content-Type' => 'application/json')
request.body = JSON.generate(body)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 3, read_timeout: 10) { |http| http.request(request) }
status = response.code.to_i
return JSON.parse(response.body) if status.between?(200, 299)
if RETRYABLE.include?(status) && attempt < max_attempts
retry_after = response['Retry-After'].to_i
sleep(retry_after.positive? ? retry_after : 2**(attempt - 1))
next
end
log_failure(response, status)
return nil
end
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError => error
Rails.logger.warn("validation skipped: #{error.class}")
nil
end
def self.log_failure(response, status)
type = JSON.parse(response.body).dig('error', 'type')
Rails.logger.warn("validation skipped: #{type} status=#{status} request_id=#{response['X-Request-Id']}")
end
end
Qelka.call returns nil whenever the check could not complete, so every validator below fails open. A 429 waits for Retry-After, and 500, 502 and 503 back off. The log line has the documented error type and the request id. See Errors.
2. Validators
Save as app/validators/deliverable_email_validator.rb:
class DeliverableEmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.blank?
result = Qelka.call('/email', { email: value })
return unless result && result['status'] == 'undeliverable'
suggestion = result['did_you_mean']
record.errors.add(attribute, suggestion ? "Did you mean #{suggestion}?" : 'cannot receive mail')
end
end
Save as app/validators/valid_phone_validator.rb:
class ValidPhoneValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if value.blank?
body = { phone: value }
country = record.try(options[:country_attribute]) if options[:country_attribute]
body[:country] = country if country.present?
result = Qelka.call('/phone', body)
return unless result
if result['status'] == 'invalid'
record.errors.add(attribute, 'is not a valid phone number')
elsif result['status'] == 'valid'
record[attribute] = result['e164']
end
end
end
The validator replaces the typed number with e164 when it is valid, so the database holds one format.
3. Use them in the model
class User < ApplicationRecord
validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, deliverable_email: true,
if: :will_save_change_to_email?
validates :phone, valid_phone: { country_attribute: :country }, if: :will_save_change_to_phone?
end
Only changed attributes are checked, so editing a profile does not pay for a new check on an unchanged email. The format check runs first and comes with Rails, so malformed input rarely costs a call.
4. Re-check what was skipped
class RecheckEmailJob < ApplicationJob
retry_on StandardError, wait: :polynomially_longer, attempts: 5
def perform(user_id)
user = User.find(user_id)
result = Qelka.call('/email', { email: user.email })
user.update_columns(needs_review: true) if result && result['status'] == 'undeliverable'
end
end
Enqueue it from an after_create callback when you could not verify the address. For IP risk, call Qelka.call('/ip', { ip: request.remote_ip }) in the controller and flag the account when risk.level is high. A 422 for a private address is normal in development.
5. Read the result
| Result | Action |
|---|---|
Email undeliverable |
Field error with did_you_mean |
Email risky or unknown |
Accept, confirm by email |
Phone invalid |
Field error |
Phone unknown |
Send the country attribute |
Phone valid |
Stored as e164 |
The limits are 200 requests per 10 seconds per key: see Rate limits. Use Rack::Attack on your signup route so bots cannot spend your credits.
Related
Frequently asked questions
Model validation or a background job?
Where do I keep the API key in Rails?
How do I avoid real calls in my test suite?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time