JS REGEX 03: Building and Validating an HTML Form Using Regular Expressions in JavaScript

Today, we’re diving into one of the most practical and powerful front-end development skills — form validation using Regular Expressions (RegEx).
When building web forms, we want users to input clean, correct, and structured data. But users can be unpredictable — someone might type 1234 as a name or hello@ as an email. To handle this gracefully, we combine RegEx and JavaScript to automatically check and validate user inputs before submission.
Let’s walk through the process step-by-step.
🏗️ Step 1: Setting Up the HTML Form
We’ll start with a simple form that collects a user’s name, email, and age. Each field will include an area to display an error message when validation fails.
<form id="myForm">
<label>
Name:
<input type="text" id="name" placeholder="Enter name (letters only)" />
<div class="error" id="nameError"></div>
</label>
<label>
Email:
<input type="text" id="email" placeholder="Enter email" />
<div class="error" id="emailError"></div>
</label>
<label>
Age:
<input type="text" id="age" placeholder="Enter age (numbers only)" />
<div class="error" id="ageError"></div>
</label>
<button type="submit">Submit</button>
</form>
🧩 What’s Happening Here
- Each
<label>holds an input and a<div>for showing error messages. - The form uses the ID
myFormso we can easily select it in JavaScript. - Placeholder text helps guide users to type the right kind of data.
🎨 Step 2: Adding Some CSS Styling
A neat and readable design makes validation feedback clear and professional. Let’s style the form with simple CSS.
body {
font-family: sans-serif;
padding: 2rem;
background: #f1f1f1;
}
label {
display: block;
margin-top: 1rem;
}
input {
width: 100%;
padding: 0.5rem;
font-size: 1rem;
margin-top: 0.3rem;
}
.error {
color: red;
font-size: 0.9rem;
}
button {
margin-top: 1rem;
padding: 0.5rem 1rem;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
}
This gives the form a soft gray background, rounded buttons, and clear red error messages for instant user feedback.
🧠 Step 3: Adding JavaScript with RegEx Validation
Here’s the heart of the lesson — validating user input using regular expressions.
const form = document.getElementById("myForm");
form.addEventListener("submit", function (e) {
e.preventDefault(); // Prevent automatic page reload
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const age = document.getElementById("age").value.trim();
// Regex patterns
const namePattern = /^[A-Za-z]+$/;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const agePattern = /^\d+$/;
// Error elements
const nameError = document.getElementById("nameError");
const emailError = document.getElementById("emailError");
const ageError = document.getElementById("ageError");
// Clear previous errors
nameError.textContent = "";
emailError.textContent = "";
ageError.textContent = "";
let valid = true;
// Validate name (letters only)
if (!namePattern.test(name)) {
nameError.textContent = "Name must contain only letters.";
valid = false;
}
// Validate email structure
if (!emailPattern.test(email)) {
emailError.textContent = "Invalid email format.";
valid = false;
}
// Validate age (numbers only)
if (!agePattern.test(age)) {
ageError.textContent = "Age must contain only digits.";
valid = false;
}
if (valid) {
alert("✅ Form is valid!");
}
});
🔍 Understanding the Logic
-
Prevent Default Submission: The
e.preventDefault()method stops the form from refreshing the page immediately after submission. -
Retrieve Input Values: We fetch and trim the values of each input field.
-
Apply RegEx Validation Rules:
^[A-Za-z]+$→ allows only letters (no numbers or spaces).^[^\s@]+@[^\s@]+\.[^\s@]+$→ ensures a valid email with@and a domain.^\d+$→ ensures only numbers for age.
-
Show Feedback:
- If any rule fails, an error message appears below the input.
- If all inputs pass, a success alert is shown.
🧪 Step 4: Testing the Form
Try different combinations to see validation in action:
| Input Example | Result | Explanation |
|---|---|---|
1234 in Name |
❌ Error | Numbers not allowed |
hello@ in Email |
❌ Error | Incomplete email address |
20years in Age |
❌ Error | Letters not allowed in age |
John, john@example.com, 25 |
✅ Valid submission | All fields correct |
Instant feedback = fewer user mistakes and cleaner data for your application.
🚀 Step 5: Practice Challenges
Want to test your skills? Here are 5 challenges to take this further:
-
Add a Phone Number Field Validate 10 digits only with
/^\d{10}$/. -
Make Name Accept Spaces and Hyphens Modify regex to
/^[A-Za-z\s-]+$/so names like “Mary-Jane Smith” are valid. -
Add Password Validation Require at least one uppercase, lowercase, digit, special symbol, and a minimum of 8 characters.
-
Replace Alert with Success Message Instead of
alert(), display a green success message below the form. -
Validate Age Range (18–99) Use JavaScript logic after regex validation to ensure
age >= 18 && age <= 99.
These mini-projects will help you gain confidence with regex and JavaScript event handling.
🧭 Why Use RegEx for Validation?
Using Regular Expressions makes your code cleaner and more efficient. Instead of writing long if chains like:
if (!email.includes("@")) { ... }
if (age.length < 2) { ... }
RegEx lets you describe your validation rule in a single elegant expression. It’s concise, fast, and easy to maintain — the true superpower of professional front-end developers.
🧩 Review Fill-Gap Questions
Let’s test your understanding. Fill in the blanks or choose the right answer:
- The regex
/^[A-Za-z]+$/ensures that the name contains only ___. - The pattern
/^\d+$/validates ___ input. - The
preventDefault()method stops the form from ___. - The regex
/^[^\s@]+@[^\s@]+\.[^\s@]+$/ensures that the email includes a ___ and a domain name. - The
.test()method in JavaScript returns ___ if the regex matches, and ___ otherwise. - In
/^[A-Za-z\s-]+$/, the\sallows ___ while the-allows ___. - The
.textContentproperty is used to display ___ messages to the user. - Which JavaScript method is used to display a pop-up success message? ___.
- How can you check that a user’s age is between 18 and 99 using JavaScript? Write a sample condition.
- Why is regex-based validation more efficient than using multiple
ifstatements?
🎯 Pro Tip
You can explore a live demo of this project on CodePen:
🌟 Final Thoughts
Form validation isn’t just about preventing errors — it’s about improving user experience and ensuring data integrity. With RegEx, you can build forms that are smarter, cleaner, and far more reliable.
Now it’s your turn: open your editor, copy the snippets, and build your own validation-powered form!