How to Use the "required" Attribute with the Radio Input Field

If you want to use the required attribute for only one input of the radio group, this snippet is for you.

Although setting the required attribute for all inputs is more clear, it is unnecessary (if you don’t need to dynamically generate radio-buttons).

To group radio buttons, they should have the same value for the name attribute. This allows us to select only one radio button at once and apply the required attribute to the whole group. Let’s see how this is done.

Create HTML

  • Use a <form> element.
  • Add three <label> elements with the radio input type, name and value attributes.
  • Add the required attribute within the first <label>.
  • Add an <input> with the type “submit”.
<form>
  Select Gender:
  <label>
    <input type="radio" name="gender" value="male" required>Male
  </label>
  <label>
    <input type="radio" name="gender" value="female">Female
  </label>
  <label>
    <input type="radio" name="gender" value="other">Other
  </label>
  <input type="submit">
</form>

Example of using the required attribute with the radio input field:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <form action="/form/submit" method="GET">
      Select Gender:
      <label>
        <input type="radio" name="gender" value="male" required>Male
      </label>
      <label>
        <input type="radio" name="gender" value="female">Female
      </label>
      <label>
        <input type="radio" name="gender" value="other">Other
      </label>
      <input type="submit">
    </form>
  </body>
</html>