Skip to content

Instantly share code, notes, and snippets.

@everton
Last active March 31, 2020 12:08
Show Gist options
  • Save everton/4e752263403d85663f397cf3d6185780 to your computer and use it in GitHub Desktop.
Save everton/4e752263403d85663f397cf3d6185780 to your computer and use it in GitHub Desktop.
Add "required" for input tags of fields with "presence" validation and "minlength" / "maxlength" of fields with "length" validation
# config/initializers/form_builder.rb
module InputTagsMarkedAsRequiredOrWithMinMaxLengthInHTMLIfValidatedForPresence
def initialize(object_name, method_name, template_object, options = {})
return super unless options[:object] # it will be nil when called from #form_with
validators = options[:object].class.validators_on(method_name)
unless options.has_key? :required # check using has_key? to allow "required: nil"
if validators.any? ActiveRecord::Validations::PresenceValidator
options[:required] = true
end
end
# They can be more than one...
length_validators = validators.select do |validator|
validator.is_a? ActiveRecord::Validations::LengthValidator
end
length_validators.each do |validator|
if options[:minlength].blank? && validator.options[:minimum]
options[:minlength] = validator.options[:minimum]
end
if options[:maxlength].blank? && validator.options[:maximum]
options[:maxlength] = validator.options[:maximum]
end
end
return super
end
end
class ActionView::Helpers::Tags::TextField
prepend InputTagsMarkedAsRequiredOrWithMinMaxLengthInHTMLIfValidatedForPresence
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment