0
0
HtmlHow-ToBeginner · 3 min read

How to Use Required Attribute for Validation in HTML Forms

Use the required attribute inside an HTML form input element to make it mandatory. When a user tries to submit the form without filling that field, the browser will show a validation message and prevent submission.
📐

Syntax

The required attribute is added directly inside an input or select element to mark it as mandatory. It does not need a value; just including it is enough.

  • <input type="text" required> means this text field must be filled.
  • <select required> means the user must select an option.
html
<input type="text" required>
💻

Example

This example shows a simple form with a required text input and a submit button. If you try to submit without typing anything, the browser will block submission and show a message.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Required Attribute Example</title>
</head>
<body>
  <form>
    <label for="name">Name (required):</label><br>
    <input type="text" id="name" name="name" required><br><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>
Output
A form with a labeled text box and a submit button. If submitted empty, the browser shows a message like "Please fill out this field."
⚠️

Common Pitfalls

Some common mistakes when using required include:

  • Adding required="false" does not disable the requirement; the attribute presence means it is required.
  • Not using required on the correct input element, so validation does not trigger.
  • Relying only on required without server-side validation, which is insecure.
html
<!-- Wrong: required="false" still makes field required -->
<input type="email" required="false">

<!-- Correct: just include required -->
<input type="email" required>
📊

Quick Reference

AttributeDescription
requiredMarks the input as mandatory; user must fill or select before submitting.
typeDefines the input type (text, email, number, etc.) which affects validation.
formAssociates input with a form if outside the form tag (optional).

Key Takeaways

Add the required attribute inside input elements to make them mandatory.
The browser prevents form submission and shows a message if required fields are empty.
Do not assign values like required="false"; presence means required.
Always combine client-side required with server-side validation for security.
Works on many input types including text, email, number, checkbox, and select.