HTML5 Required Attribute

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 :
HTML5 Required Attribute
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:
HTML5 Required Attribute1

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*