Last active
March 29, 2018 05:40
-
-
Save fongfan999/58ae89390ba07ba0e81e03aa5b368054 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StringMaxLengthValidator < ActiveModel::EachValidator | |
STRING_MAX_LENGTH = 255 | |
def validate_each(record, attribute, value) | |
return if string_length_in_range?(value) | |
record.errors.add attribute, :'too_long.other', count: STRING_MAX_LENGTH | |
end | |
private | |
def string_length_in_range?(str) | |
str.present? && str.length <= STRING_MAX_LENGTH | |
end | |
end | |
module ActiveModel | |
module Validations | |
module HelperMethods | |
# Validates that the specified attributes match the string maximum length | |
# restrictions supplied. | |
# | |
# class Person < ActiveRecord::Base | |
# validates :first_name, string_max_length: true | |
# validates_string_max_size_of :middle_name, :last_name | |
# end | |
def validates_string_max_length_of(*attr_names) | |
validates_with StringMaxLengthValidator, _merge_attributes(attr_names) | |
end | |
alias_method :validates_string_max_size_of, :validates_string_max_length_of | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment