JavaScript - How to Validate Form Using Regular Expression?
Last Updated :
03 Dec, 2024
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.
JavaScript
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");
}
OutputValid 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.
JavaScript
let regex = /^\d{10}$/;
let phone = "1234567890";
if (regex.test(phone)) {
console.log("Valid phone number");
} else {
console.log("Invalid 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.
JavaScript
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");
}
- ^(?=.*[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.
JavaScript
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.
JavaScript
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");
}
- ^(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
<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.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
HTML Tutorial HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read