required

In HTML, the required attribute indicates that an input field must be filled out before the form can be submitted, preventing submission until the field is completed.

required attribute

The required attribute ensures that a user must enter a value in the input field before submitting the form.

Syntax

index.html
<tagname required>

Example




index.html
<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br><br>
  <button type="submit">Submit</button>
</form>

Values

The required attribute is a boolean attribute and does not have any associated values.

Applies To

The required attribute can be applied to the following HTML elements.

Key Points

  • Purpose: Makes an input field mandatory.
  • Supported Elements: <input> (text, email, password, etc.), <select>, <textarea>.
  • Not Supported: <range>, color, hidden, and button types.
  • Group Behavior: For radio buttons, only one needs to be checked. For checkboxes, only those with required are mandatory.

Usability

  • Clear Indicator: Provide a noticeable sign that the field is mandatory.
  • Accessibility: Implement both the required attribute and aria-required="true" for improved support with screen readers.
  • Constraint Validation Pseudo-class: Activates when a required field is not filled out.

Conclusion

The required attribute ensures that users must fill in specific fields before submitting a form. It is applied to elements like <input>,<textarea>, and <select>, making certain fields mandatory. This helps improve form validation and ensures necessary data is provided.