Last active
October 13, 2015 09:18
-
-
Save mlr/4173895 to your computer and use it in GitHub Desktop.
Add a "required" CSS class for inputs that are required using validates_presence_of
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
# Adds a required css class to the label if the field | |
# is required in the model using a presence validator | |
# You need to place this in a file that will be autoloaded | |
# or required manually into your project. The initializers | |
# folder is autoloaded, but you might already have a better | |
# place where you load in similar things for your project. | |
# Add this to your css: | |
# | |
# label.required:after { | |
# padding-left: 2px; | |
# font-size: 14px; | |
# content: "*"; | |
# color: #C00; | |
# } | |
module ActionView | |
module Helpers | |
class FormBuilder | |
def label(method, text = nil, options = {}, &block) | |
classes = [] | |
classes << "required" if has_presence_validator? object, method | |
options.reverse_merge! class: classes | |
@template.label(@object_name, method, text, objectify_options(options), &block) | |
end | |
private | |
def has_presence_validator? object, method | |
has_validator? object, method, ActiveRecord::Validations::PresenceValidator | |
end | |
def has_validator? object, method, validator | |
validator = object.class.validators_on(method).detect do |v| | |
v.is_a? validator | |
end | |
if validator | |
context = object.persisted? ? :update : :create | |
validator.options.empty? || validator.options[:on] == context | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment