JavaScript - How to Validate Form Using Regular Expression?
To validate a form in JavaScript, you can use Regular Expressions (RegExp) to ensure that user input follows the correct format. In this article, we'll explore how to validate common form fields such as email, phone number, and password using RegExp patterns.
1. Validating an Email Address
One of the most common form fields to validate is the email address. We can use a RegExp pattern to ensure the email is in the correct format.
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
let mail = "test@example.com";
if (regex.test(mail)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
Output
Valid email address
- ^[a-zA-Z0-9._%+-]+: Matches the local part (before the @) which can include letters, numbers, and certain special characters like ., %, +, -.
- @[a-zA-Z0-9.-]+: Matches the domain part (after the @), which can contain letters, numbers, hyphens, and periods.
- \.[a-zA-Z]{2,}$: Ensures the email ends with a valid top-level domain (e.g., .com, .org).
2. Validating a Phone Number
Next, let's validate a phone number. Phone number formats vary by region, but we’ll use a basic pattern to validate a typical 10-digit phone number.
let regex = /^\d{10}$/;
let phone = "1234567890";
if (regex.test(phone)) {
console.log("Valid phone number");
} else {
console.log("Invalid phone number");
}
Output
Valid phone number
^\d{10}$: Matches exactly 10 digits. The \d stands for a digit, and {10} ensures exactly 10 digits are present.
3. Validating a Password
Passwords often require certain criteria to be met, such as a minimum length, at least one uppercase letter, one lowercase letter, and a number. We can use a RegExp to validate these conditions.
let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
let pass = "Password123";
if (regex.test(pass)) {
console.log("Valid password");
} else {
console.log("Invalid password");
}
Output
Valid password
- ^(?=.*[a-z]): Ensures at least one lowercase letter.
- (?=.*[A-Z]): Ensures at least one uppercase letter.
- (?=.*\d): Ensures at least one digit.
- [a-zA-Z\d]{8,}$: Ensures the password is at least 8 characters long and only contains letters and digits.
4. Validating a Username
Usernames often have specific rules, such as no spaces, must start with a letter, and can only contain letters, numbers, and underscores. Here's how to validate that.
let regex = /^[a-zA-Z][a-zA-Z0-9_]{5,19}$/;
let uName = "user_123";
if (regex.test(uName)) {
console.log("Valid username");
} else {
console.log("Invalid username");
}
- ^[a-zA-Z]: Ensures the username starts with a letter.
- [a-zA-Z0-9_]{5,19}$: Ensures the username is between 6 to 20 characters long and can contain letters, numbers, and underscores.
5. Validating a URL
For form fields where users need to input a URL, we can use a regular expression to ensure the URL is in the correct format.
let regex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
let url = "https://www.example.com";
if (regex.test(url)) {
console.log("Valid URL");
} else {
console.log("Invalid URL");
}
Output
Valid URL
- ^(https?|ftp):\/\/: Matches the protocol (http, https, or ftp) followed by ://.
- [^\s/$.?#].[^\s]*$: Ensures the rest of the URL is properly formed, including domain, path, and query parameters.
Integrating Form Validation with HTML
To validate the form inputs, you can call the above RegExp checks when the user submits the form. Here’s an example of how to implement form validation using JavaScript
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.form-container {
width: 300px;
margin: 100px auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
h2 {
text-align: center;
margin-bottom: 20px;
}
input {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
button {
width: 100%;
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="form-container">
<h2>Form Validation</h2>
<form id="myForm">
<input type="email" id="email" placeholder="Enter your email" required />
<input type="text" id="phone" placeholder="Enter your phone number" required />
<input type="password" id="password" placeholder="Enter your password" required />
<button type="submit">Submit</button>
</form>
</div>
<script>
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the form from submitting
// Get the values from the form
let email = document.getElementById("email").value;
let phone = document.getElementById("phone").value;
let password = document.getElementById("password").value;
// Regular Expressions for validation
let emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
let phoneRegex = /^\d{10}$/;
let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,}$/;
// Validate email
if (!emailRegex.test(email)) {
alert("Invalid email address!");
return;
}
// Validate phone number
if (!phoneRegex.test(phone)) {
alert("Invalid phone number. Must be 10 digits.");
return;
}
// Validate password
if (!passwordRegex.test(password)) {
alert("Password must be at least 8 characters, including uppercase, lowercase, a number, and a symbol.");
return;
}
// If all validations pass
alert("Form submitted successfully!");
// Clear the form after successful submission
document.getElementById("myForm").reset();
});
</script>
</body>
</html>
- This script listens for the form submission event and prevents the default behavior using event.preventDefault().
- It checks the email, phone number, and password fields using the corresponding RegExp patterns.
- If any field fails validation, an alert message is shown. If all validations pass, the form is considered successfully submitted.