Save 36% for Black Friday! Learn more

Want more GoRails?

GoRails is packed full with 721 lessons just like this one.

Sign up to get full access or log in to your account and sit back.

How to Build Custom ActiveRecord Validations

September 20, 2021

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Custom ActiveRecord validations are easy to make and they're implemented exactly the same way as the built-in Rails validations. It's super handy to be able to add nice, clean validations that you can repeat throughout your apps.

Notes

Resources

Here's our example Resizable Image Validator that validates image content types that are uploaded. We can make sure we only accept image types that are resizable using this validator.

# app/validators/resizable_image_validator.rb
class ResizableImageValidator < ActiveModel::EachValidator
  # Only allow resizable image formats
  # SVGs aren't allowed because they can contain XSS
  #
  def validate_each(record, attribute, value)
    return unless value.attached?

    if ActiveStorage.variable_content_types.exclude?(value.content_type)
      record.errors.add(attribute, :image_format_not_supported)
    end
  end
end
# app/models/user.rb
class User < ApplicationRecord
  has_one_attached :avatar
  validates :avatar, resizable_image: true
end

Want to stay up-to-date with Ruby on Rails?

Join 87,110+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.