This project is archived and is in readonly mode.

#1238 ✓committed
Vladimir Dobriakov

FormTagHelper generates illegal html if name contains e.g. square brackets

Reported by Vladimir Dobriakov | October 20th, 2008 @ 04:32 PM | in 2.x

ActionView::Helpers::FormHelper works perfectly and uses sanitized_object_name() to create the html element id. In contrast, the ActionView::Helpers::InstanceTag methods, e.g. text_field_tag simply pass the name parameter as an id to the tag method, creating invalid html for a valid name parameter:

tag :input, { "type" => "text", "name" => name, "id" => name, ...

According to the documentation of ActionView::Helpers::FormTagHelper#text_field_tag 'name' is expected as parameter. If I provide a legal name, e.g. 'widget[existing_archive_attributes][-1][filename]' an illegal html is created. The id attribute with square brackets is not allowed.

To fix the problem following methods in the FormTagHelper should be adjusted: select_tag, text_field_tag, label_tag, check_box_tag. For example, as follows:

  def select_tag(name, option_tags = nil, options = {})
    content_tag :select, option_tags, { "name" => name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)

  def text_field_tag(name, value = nil, options = {})
    tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)

  # hidden_field_tag is based on text_field_tag so no patching needed

  def label_tag(name, text = nil, options = {})
    content_tag :label, text || name.humanize, { "for" => sanitize_to_id(name) }.update(options.stringify_keys)

  def check_box_tag(name, value = "1", checked = false, options = {})
    html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
    html_options["checked"] = "checked" if checked
    tag :input, html_options


  def sanitize_to_id(name)
    name.to_s.gsub(/[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>

People watching this ticket


Referenced by