The required attribute is a form attribute introduced in HTML5. It is used to notify that we have to fill the particular field with some data before submitting the form. This attribute can be used for validations, which otherwise was done using JavaScript code. This attribute saves a lot of development time (validation code development) . The required attribute is of type Boolean. This tutorial explains the basic usage of required attribute with simple example.
Syntax of required Attribute
<input type= "string" required>
HTML5 Required Example
<!DOCTYPE html> <head> <title> Required Attribute</title> </head> <body> <form> Name <input type="text" required><br> Surname<input type="text" required><br> DOB <input type="text" required><br> Residential Address<input type="text" required><br> Phone Number <input type="text" required><br><br> <input type="submit" value="Submit"> </form> </body> </html>
In this example we are validating all the fields using the required attribute. Now suppose you don’t enter the fields with values and click on submit button, a validation error occurs and a message is displayed.
Example Application Test
- Save the file as required_example.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML5 specification.
Output
When the execution process is completed successfully we will get the following output :
Now click on the submit button without entering any values in the fields, a validation error occurs and an output as below would be seen: