What is the required attribute in HTML?

Overview

In this shot, we’ll learn about the required attribute in HTML.

This attribute is used while taking input from a user in a form and wants to restrict the user from submitting the form unless they fill in the necessary information that we need.

For example, If we register a user into our website, email and password are necessary. And we can put other fields such as gender as optional. We can restrict the user to submit the form only if he enters the email and password fields.

We can use the required attribute on the input element to restrict the user from submitting the form only if they enter the required fields.

We can use this attribute in the following way:

Syntax

<input required>

Example

Let’s look at an example.

<html>
<head>
</head>
<body>
<div id="content">
<form >
<label for="email">Email:</label>
<!-- provide required attribute -->
<input id="email" type="text" required>
<br />
<label for="password">Password:</label>
<!-- provide required attribute -->
<input id="password" type="password" required>
<br />
<label for="gender">Gender:</label>
<input id="gender" type="text" >
<input type="submit">
</form>
</div>
</body>
</html>

Explanation

In the above code snippet:

  • Line 10: We take email as required information from the user, so we apply the required attribute for the input element.

  • Line 16: We take password as required information from the user, so we apply the required attribute for the input element.

  • Line 21: We take gender input as optional, so we do not apply the required attribute on the gender input element.

  • In Line 23: We create an input element of type submit used to submit the form.

Output

Click the submit button in the below output after running it.

We can try different ways by filling some fields. For example, try to fill only the email field and click the submit button. After that, the form also asks us to fill out the password field as it is a required field.

Free Resources