The required attribute is used to make an input field mandatory before submitting a form. It helps ensure that users fill in important fields.
- Prevents form submission if the input field is left empty.
- Commonly used with text fields, email inputs, checkboxes, and other form elements.
- It is a boolean attribute, so its presence alone makes the field required.
Syntax:
<input required> Example 1: Illustrates the use of required attribute in input Element.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
required Attribute
</title>
<style>
h1,
h2 {
color: green;
font-style: italic;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>GeeksForGeeks</h1>
<h2>
HTML input required attribute
</h2>
<!--Driver Code Ends-->
<form action="">
Username:
<input type="text"
name="username"
required>
<br> Password:
<input type="password"
name="password">
<br>
<input type="submit">
</form>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
Example 2: Illustrates the use of required attribute in input Element.
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
required Attribute
</title>
<style>
h1,
h2 {
color: green;
font-style: italic;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>GeeksForGeeks</h1>
<h2>
HTML input required attribute
</h2>
<!--Driver Code Ends-->
<form action="">
Required:
<input type="radio"
name="radiocheck"
required>
<br>
<input type="submit">
</form>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->