How to Make Input Field Required in HTML

In this tutorial, we will learn how to make input field required in HTML. When you are creating a form, you want a user to fill the input field with the required data.

To make the input field required, we have to use the required attribute. The required attribute is a Boolean attribute, which is used to specify that the user should enter the required data before submitting the form. This required attribute can also be used in other form inputs like radio, checkbox, or text.

In the following example, we will make an input field required and prevent form submission. Please have a look over the code example and the steps given below.

HTML

  • In the HTML file, we have 3 elements (form, label, and input).
  • The label element is used to specify a label for an input field. The value of for attribute is set to the name of the corresponding input field.
  • The input element specifies an input field where the user can enter data.
  • The input has a type attribute with a value of the text and an id attribute with a value of name. The required attribute specifies that the user should enter the required data before submitting the form. If user do not fill it, the form will not be submitted.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input field required</title>
</head>

<body>

    <label for="name">Name:</label>
    <input type="text" id="name" required>


</body>

</html>