How to use the required attribute in form validation in HTML

An HTML attribute provides additional information about an HTML element. HTML elements are a particular part of an HTML page that defines the web page's structure, behavior, or layout.

<a href="www.educative.io">This is an "anchor" element with an "href" attribute.</a>

Let's learn how to use the required attribute within HTML elements.

Use the required attribute

The required attribute is used with several data input elements, such as input, select, and textarea. The required attribute is simply added in the brackets of the opening tag. When added, the required attribute signifies that the field must be filled out before form submission.

<form action="/nextPage.jsp">
<label for="username">Username:</label>
<input type="text" id="userName" name="username" required><br>
<input type="submit" value="Submit form">
</form>
An example of a form where users are required to enter their usernames

After proper form validation, the browser will automatically display an error and force users to fill in the input field. Almost all major browsers' versions support this attribute.

Note: The required attribute is a boolean attribute which means that its either present/true or absent/false. If present, users will have to input data in the field and failing to do so will generate an error.

Take a look at the example below; the highlighted lines 10–19 show the code where there are two forms. If not filled and submitted, the first form will notify the user. The second form, where the required attribute is missing, throws no error and allows submission.

Click the "Run" button below to render the page.

Benefits

Some of the key advantages of using the required attribute are as follows:

  • Better user guidance is achieved through visual appearance. Even users with disabilities get support.

  • Since browsers have built-in support for required attributes, there is little effort needed to add the feature for coding and validation purposes.

Alternatives to required attribute

Forms are validated on the frontend or the backend or both – which is usually the recommended strategy. While the required is a frontend validation technique, other techniques that can do form validations are:

  • Validation through JavaScript: An alternative to using the required field is validation through JavaScript. While JavaScript may be used to meet complex form validation goals, it is a hassle to use JavaScript to ensure basic form validation needs.

  • Backend validation: Another name for this type of validation is server-side validation. User form input data should be validated on the server-side because users can modify client-side code. Thus, any security lapses can be avoided.

The required attribute provides improved data quality, experience, and security.

Copyright ©2024 Educative, Inc. All rights reserved