The HTML required attribute can be used to specify whether the element must be filled out or not before submitting the form. It is a boolean attribute that requires boolean values like true and false.
Example: Form with Required input field
1 2 3 4 5 6 7 |
<form> <label for="username">Username</label> <input type="text" name="username" required><br><br> <label for="email">Email</label> <input type="email" name="email" required><br><br> <input type="submit" name="submit" value="submit"> </form> |
Output
It works and applicable to all <input>
types(like text, checkbox, radio, password, email, etc), <select>
, and <textarea>
elements of HTML.
Input Field with Required Attribute
To make the input field required, you have to use the syntax given below:-
Syntax
There are many input types that you can make required by adding the required
attribute to the <input> tag. See the example below showing the HTML required attribute in input fields.
Example: Form with Required input field
1 2 3 4 5 6 7 |
<form> <label for="username">Username</label> <input type="text" name="username" required><br><br> <label for="email">Email</label> <input type="email" name="email" required><br><br> <input type="submit" name="submit" value="submit"> </form> |
Output
Select Box With Required Attribute
Syntax
To make a select box compulsory to be filled by the user, you have to use the required
attribute as given in the example below:-
Example: Form with required select box
1 2 3 4 5 6 7 8 9 10 11 |
<form> <label for="name">Name</label> <input type="text" name="name" required><br><br> <label for="country">Select Country</label> <select name="country" required> <option value="India">India</option> <option value="US">US</option> <option value="Australia">Australia</option> </select><br><br> <input type="submit" name="submit" name="submit"> </form> |
Output
The above example showing the select field with HTML required attribute added at the end of <select> tag.
Textarea with Required Attribute
Syntax
The required
attribute in HTML is also useful when you want to make the <textarea> field required. A textarea field is helpful to get the comments and messages from users. By making it required, you can easily force users to fill it before submitting the form.
Example: Form with required textarea box
1 2 3 4 5 6 7 |
<form> <label for="name">Name</label> <input type="text" name="name" required><br><br> <label for="Message">Message</label> <textarea name="message" rows="3" col="8" required></textarea><br><br> <input type="submit" name="submit" name="submit"> </form> |
Output
Browser Compatibility
The required
attribute in HTML supports the following browsers:-
- Google Chrome
- Internet Explorer
- Firefox
- Opera Mini