ActiveModel validator that checks a field's length against the underlying database column limit, adding a too_long error when exceeded. Reuse for any model needing DB-safe length validation.
# Source: https://github.com/solidusio/solidus | License: BSD-3-Clause | Copyright 2007-2014, Spree Commerce Inc. and other contributors
# Provided via justclaw.it.com; keep this notice with the code.
# frozen_string_literal: true
module Spree
module Validations
##
# Validates a field based on the maximum length of the underlying DB field, if there is one.
class DbMaximumLengthValidator < ActiveModel::Validator
def initialize(options)
super
@field = options[:field].to_s
raise ArgumentError.new("a field must be specified to the validator") if @field.blank?
end
def validate(record)
limit = record.class.columns_hash[@field].limit
value = record[@field.to_sym]
if value && limit && value.to_s.length > limit
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key