JS REGEX 03: Building and Validating an HTML Form Using Regular Expressions in JavaScript
Today, we’re diving into one of the most useful front-end development skills — form validation using Regular Expressions (RegEx).
Imagine you’re creating a simple registration form that collects a user’s name, email, and age. You want to make sure users don’t enter something weird like 1234
for their name or hello@
for their email.
That’s where RegEx and a bit of JavaScript come in. Let’s roll up our sleeves and get started!
🏗️ Step 1: Setting Up the HTML Form
Start by creating a basic form structure inside your HTML file. This will include three input fields — name, email, and age — along with space to display error messages.
<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>
🧩 How It Works
- Each
<label>
contains an input and a<div>
for error messages. - The entire form has an
id="myForm"
, making it easy to select with JavaScript. - Placeholder text gives users hints about what to type.
🎨 Step 2: Adding CSS Styling
You don’t want your form to look dull, right? Let’s style it up a bit for readability and comfort.
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 clean, modern look and highlights error messages in red, making them easy to notice.
🧠 Step 3: Writing the JavaScript for Validation
Here comes the fun part — adding regex-based validation logic.
const form = document.getElementById("myForm");
form.addEventListener("submit", function (e) {
e.preventDefault(); // Stop the default form submission
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 message 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 format
if (!emailPattern.test(email)) {
emailError.textContent = "Invalid email format.";
valid = false;
}
// Validate age: numbers only
if (!agePattern.test(age)) {
ageError.textContent = "Age must be numbers only.";
valid = false;
}
if (valid) {
alert("✅ Form is valid!");
}
});
🔍 How It Works
- Prevent Form Submission – The first line stops the page from reloading when you press “Submit.”
- Fetch Values – It gets the text inside the inputs.
-
Use RegEx to Check Patterns –
^[A-Za-z]+$
→ Only letters allowed for name.^[^\s@]+@[^\s@]+\.[^\s@]+$
→ Checks for a valid email structure.^\d+$
→ Only digits allowed for age.
-
Show Errors or Success –
- If validation fails, it shows an error message below the field.
- If all inputs are correct, it pops up a success alert.
🧪 Step 4: Test Your Form
Now open your file in a browser and play with it. Try entering:
Input | Expected Result |
---|---|
1234 in Name |
❌ Error – letters only |
hello@ in Email |
❌ Error – missing domain |
20years in Age |
❌ Error – letters not allowed |
John , john@example.com , 25 |
✅ Success alert! |
Instant feedback means better user experience and cleaner data for your application.
🚀 Step 5: Practice Challenges
Want to take it further? Here are five hands-on upgrades to level up your validation game:
-
Add a Phone Number Field Validate it using RegEx to allow only 10 digits.
-
Make Name Accept Spaces and Hyphens Update the pattern to allow “Mary-Jane Smith”. (Hint: Use
[A-Za-z\s-]+
) -
Add a Password Field Require at least one uppercase, one lowercase, one digit, one symbol, and a minimum of 8 characters.
-
Replace Alert with Success Message Instead of an alert, show a green “Form submitted successfully!” text under the form.
-
Validate Age Range (18–99) Use JavaScript to check that age is between 18 and 99 after confirming it’s numeric.
Each of these mini-projects strengthens your grasp of regex and JavaScript event handling.
🧭 Final Thoughts
Using Regular Expressions in form validation helps you:
- Keep input data clean and predictable.
- Improve user experience with instant feedback.
- Avoid long, messy conditional statements.
This small project is the perfect foundation for building more advanced forms — such as sign-up pages, contact forms, and survey inputs — that work smoothly and securely.
So go ahead — open your text editor, paste the code, and make it your own!
🧩 Review Fill-Gap Questions
Let’s see how much you remember. Fill in the blanks or choose the right answer:
1. The regex /^[A-Za-z]+$/
ensures that the name contains only ___.
2. The pattern /^\d+$/
is used to validate ___ input.
3. In the form’s JavaScript, the method preventDefault()
stops the form from ___.
4. To check for a valid email, the regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/
looks for a ___ symbol and a domain extension.
5. The .test()
method in JavaScript returns ___ if the regex matches, otherwise ___.
6. To allow spaces and hyphens in a name, modify the regex to /^[A-Za-z\s-]+$/
. What do \s
and -
represent?
7. What kind of feedback does the .textContent
property update for each input?
8. Which function is used to display a pop-up success message?
9. How could you check that the user’s age is between 18 and 99 using JavaScript logic after regex validation?
10. Why is regex-based validation preferred over multiple if
statements in forms?
🎯 Pro Tip: You can explore this live example here:
Now go forth, young coder — make your forms smart, stylish, and regex-ready!