Boolean attributes in HTML

In HTML, some special attributes are called boolean attributes. They’re unique because it’s the mere presence of the attribute that matters. If the attribute is present, it’s considered truthy, regardless of its value. If it’s omitted altogether, it’s considered falsy. Some examples are required, disabled, and hidden.

Valid examples

If you want to mark an input as a required field, you should add the required attribute in one of three ways.

You can omit the value altogether:

<input type="text" name="name" required>

Or set it to an empty string:

<input type="text" name="name" required="">

Or set it to the same name as the attribute itself:

<input type="text" name="name" required="required">

All of the above are valid HTML, although I prefer the first two.

As explained in the MDN Web Docs:

HTML5 defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace.

Invalid examples

You should neither do this:

<input type="text" name="name" required="true">

Nor this:

<input type="text" name="name" required="false">

Both of these are invalid HTML.

Worse still: even if you set required="false", it will still be truthy. The MDN Web Docs explain:

To be clear, the values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. This restriction clears up some common misunderstandings: With checked="false" for example, the element’s checked attribute would be interpreted as true because the attribute is present.

Summary

You can set a boolean attribute in one of three ways:

  1. Omit the value (e.g. required)
  2. Use an empty string (e.g. required="")
  3. Use the name of the attribute itself (e.g. required="required")

You should not use any other strings—not even true or false.

For more information, check out Boolean Attributes in the MDN Web Docs.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!