2013-02-16 09:58:33 +08:00
|
|
|
class StrippedLengthValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
unless value.nil?
|
|
|
|
stripped_length = value.strip.length
|
2013-04-10 20:54:10 +08:00
|
|
|
# the `in` parameter might be a lambda when the range is dynamic
|
|
|
|
range = options[:in].lambda? ? options[:in].call : options[:in]
|
2013-02-19 10:57:46 +08:00
|
|
|
record.errors.add attribute, (options[:message] || I18n.t('errors.messages.too_short', count: range.begin)) unless
|
2013-02-16 09:58:33 +08:00
|
|
|
stripped_length >= range.begin
|
2013-02-19 10:57:46 +08:00
|
|
|
record.errors.add attribute, (options[:message] || I18n.t('errors.messages.too_long', count: range.end)) unless
|
2013-02-16 09:58:33 +08:00
|
|
|
stripped_length <= range.end
|
|
|
|
else
|
2013-02-19 10:57:46 +08:00
|
|
|
record.errors.add attribute, (options[:message] || I18n.t('errors.messages.blank'))
|
2013-02-16 09:58:33 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|