Build a Contact Form with Input Validation Attributes (required
, maxlength
) in HTML
Creating a contact form is one of the first projects many beginners try in HTML. It allows users to send their name, email, message, and other information to a website owner.
In this tutorial, you will build a simple contact form and learn how to use two powerful HTML validation attributes:
-
required
– ensures the user doesn’t leave a field empty -
maxlength
– limits the number of characters a user can enter
Let’s get started step-by-step! ✅
🔹 Step 1: Basic HTML Structure
First, every HTML page needs a basic structure.
🔍 Explanation:
-
<!DOCTYPE html>
: Declares the document is HTML5. -
<html lang="en">
: Sets language to English. -
<head>
: Contains metadata like the page title. -
<body>
: Where the actual visible content goes.
🔹 Step 2: Add a Form Element
🔍 Explanation:
-
<form>
: Starts the form. -
action="#"
: Normally, this is where the data is sent. For now, we leave it as#
since we’re not connecting to a server. -
method="post"
: Specifies how form data will be sent.
🔹 Step 3: Add Input Fields with Validation
Here’s a simple contact form:
🔍 Field-by-Field Explanation:
🧍 Name Input:
-
type="text"
: Accepts plain text. -
id
andname
: Identifiers for the input. -
required
: The user must fill this in. -
maxlength="50"
: User cannot type more than 50 characters.
📧 Email Input:
-
type="email"
: Checks for a valid email format (e.g., name@example.com). -
required
: Can't submit the form if this is empty. -
maxlength="100"
: Limits to 100 characters.
💬 Message Textarea:
-
<textarea>
: Multi-line text input for longer messages. -
required
: Field is mandatory. -
maxlength="300"
: Only 300 characters allowed.
✅ Submit Button:
-
Sends the form data when clicked.
🧪 Built-in Validation in Action
When you try to submit the form without filling out the required fields, the browser will show an automatic message like:
“Please fill out this field.”
And if the input is too long, the browser will stop the user from typing further.
No JavaScript needed – this is pure HTML validation!
💡 Pro Tips
-
Always use
required
for important fields to ensure you collect needed information. -
Use
maxlength
to protect against very long and messy inputs. -
Combine these with
type="email"
ortype="number"
for extra input control.
✅ Final Code
🏁 Conclusion
Using required
and maxlength
in HTML makes your contact forms much more user-friendly and secure – and the best part? You don’t need JavaScript to do it!