This came up in https://github.com/backdrop/backdrop-issues/issues/647#issuecomment-1368... and elsewhere before. In that issue, there was an attempt to use a field of '#type' => 'machine_name' in order to provide uniqueness for the CSS ID, as well as to provide some basic validation, but it was not ideal (hence this issue here).

Since both core and contrib modules have fields in their settings forms that prompt for CSS class(es)/ID(s), having specific FAPI elements for that would provide for a consistent feature, and reduce/reuse code.

We should add either a single '#type' => 'css_attribute' FAPI element (a better name?) for entering both CSS classes/IDs, or two separate ones of '#type' => 'css_classes' and '#type' => 'css_id', that: - Perform validation OOTB, without requiring developers to write their own custom submit handlers. A regex of ^[a-zA-Z]{1}[a-zA-Z0-9_-]+$ should be enough to provide some basic validation, but if we want to cover all edge cases, then we should follow the spec in https://www.w3.org/TR/CSS2/syndata.html#characters more precisely:

  • All CSS syntax is case-insensitive within the ASCII range (i.e., [a-z] and [A-Z] are equivalent), except for parts that are not under the control of CSS. For example, the case-sensitivity of values of the HTML attributes "id" and "class", of font names, and of URIs lies outside the scope of this specification. Note in particular that element names are case-insensitive in HTML, but case-sensitive in XML.
  • In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
  • Provide a default help text (#description property), so that developers don't need to add one unless required to be different.

Noting here that although the "separate each class with a space" text is common, it is not ideal UX. We should be allowing people to enter classes separated either by commas or spaces, and then automatically remove any commas during validation - no need to be bothering people with instructions around what format we expect CSS classes to be in when we can do better.

GitHub Issue #: 
5898