Rails validators for custom business logic

Maya Patel Jan 2026
2 tabs
class SlugValidator < ActiveModel::Validator
  SLUG_REGEX = /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/

  def validate(record)
    slug = record.send(options[:attribute] || :slug)

    if slug.blank?
      record.errors.add(:slug, 'cannot be blank')
      return
    end

    unless slug.match?(SLUG_REGEX)
      record.errors.add(:slug, 'must contain only lowercase letters, numbers, and hyphens')
    end

    if slug.length < options[:minimum] || slug.length > options[:maximum]
      record.errors.add(:slug, "must be between #{options[:minimum]} and #{options[:maximum]} characters")
    end

    # Check for reserved words
    reserved_slugs = %w[admin api new edit delete]
    if reserved_slugs.include?(slug)
      record.errors.add(:slug, 'is reserved and cannot be used')
    end
  end
end
2 files · ruby Explain with highlit

Custom validators encapsulate complex validation rules that go beyond built-in validators. I create validator classes for business logic like email format verification, slug uniqueness, or credit card validation. Custom validators inherit from ActiveModel::Validator and implement a validate method that adds errors to the record. They're reusable across models and testable in isolation. For simple one-off validations, I use validate with a method name. Complex conditional validations use if/unless options. I keep validators focused—each validates one concern. Error messages use I18n for internationalization. This pattern keeps models clean while enforcing business rules consistently.