Skip to content

Instantly share code, notes, and snippets.

@tony612
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save tony612/b60be902304366237489 to your computer and use it in GitHub Desktop.

Select an option

Save tony612/b60be902304366237489 to your computer and use it in GitHub Desktop.
A nice way to add asterisk* to "required" field in frontend used with https://github.com/amatsuda/html5_validators
# config/initializers/label_required.rb
module ActionView
module Helpers
# For rails 4
if ActionPack::VERSION::STRING >= '4'
module Tags
class Label
def render_with_required(&block)
inject_required_field
render_without_required &block
end
alias_method_chain :render, :required
end
end
else
# For rails 3, but not tested
class InstanceTag
def to_label_tag_with_required(text = nil, options = {}, &block)
if object.class.ancestors.include? ActiveModel::Validations
options["required"] ||= object.class.attribute_required?(method_name)
end
to_label_tag_without_required text, options, &block
end
alias_method_chain :to_label_tag, :required
end
end
end
end
// For bootstrap
label.control-label[required='required']:before {
content: "* ";
color: red;
}
label:not(.control-label)[required='required']:after {
content: " *";
color: red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment