Created
July 11, 2018 03:39
-
-
Save EhsanZ/275ba309cb1c21a39d98e4793d545448 to your computer and use it in GitHub Desktop.
Rails 5 Array Length Custom Validator
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 ArrayLengthValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
return unless validate_options(options, value) | |
array_size = value.size | |
minimum = options[:minimum] || array_size | |
maximum = options[:maximum] || array_size | |
error = get_error(array_size, minimum, maximum) | |
return if error.blank? | |
record.errors[attribute] << I18n.t("errors.messages.#{error}.other") | |
end | |
protected | |
def validate_options(options, value) | |
return false unless options.key?(:minimum) || options.key?(:maximum) | |
return false unless value.respond_to?(:size) | |
true | |
end | |
def get_error(array_size, minimum, maximum) | |
if array_size > maximum | |
"too_long" | |
elsif array_size < minimum | |
"too_short" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment