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 = "[email protected]";
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 - How to Use a Variable in Regular Expression?
To dynamically create a regular expression (RegExp) in JavaScript using variables, you can use the RegExp constructor. Here are the various ways to use a variable in Regular Expression.1. Using the RegExp Constructor with a VariableIn JavaScript, regular expressions can be created dynamically using
3 min read
How to validate HTML tag using Regular Expression
Given string str, the task is to check whether it is a valid HTML tag or not by using Regular Expression.The valid HTML tag must satisfy the following conditions: It should start with an opening tag (<).It should be followed by a double quotes string or single quotes string.It should not allow on
6 min read
How to Validate Email Address using RegExp in JavaScript?
Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.Why Validate Email Addresses?Validating email addresses is important for a number of reasons
3 min read
How to Validate Email Address without using Regular Expression in JavaScript ?
Email validation in JavaScript is the process of ensuring that an email address entered by the user is in the correct format and is a valid email address or not. This is typically done on the client side using JavaScript before the form is submitted to the server.An email address must have the follo
5 min read
How to check for IP address using regular expression in javascript?
The task is to validate the IP address of both IPv4 as well as IPv6. Here we are going to use RegExp to solve the problem. Approach 1: RegExp: Which split the IP address on. (dot) and check for each element whether they are valid or not(0-255). Example 1: This example uses the approach discussed abo
2 min read
JavaScript - How to Create Regular Expression Only Accept Special Formula?
To ensure that a string matches a specific formula or pattern, you can use a regular expression (RegExp) in JavaScript. Here are the various ways to create a regular expression that only accepts regular formulas.1: Alphanumeric Code FormulaLet's create a regular expression that matches a formula lik
3 min read
How to Validate String Date Format in JavaScript ?
Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation. There are many ways by which we can validate whether the D
5 min read
JavaScript - How Useful is Learning Regular Expressions?
Regular expressions (RegExp) are an important skill for JavaScript developers that helps in text manipulation, validation, and extraction. Whether youâre working on form validations, file handling, or log parsing, mastering regular expressions can simplify your code and improve productivity. Why Lea
3 min read
Regular Expressions to Validate Google Analytics Tracking Id
Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the g
5 min read
Convert user input string into regular expression using JavaScript
In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object
2 min read