🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Validating a phone number is an important task in web development to ensure users provide a correctly formatted number. A phone number typically follows specific patterns depending on the country, and it can include digits, spaces, parentheses, hyphens, and a leading country code (e.g., +1). This guide will walk you through writing a JavaScript program to validate a basic phone number using regular expressions (regex).
Problem Statement
Create a JavaScript program that:
- Accepts a phone number from the user.
- Validates whether the phone number is in the correct format.
- Displays whether the phone number is valid or invalid.
Example:
Input:
"123-456-7890"Output:
The phone number is valid.Input:
"5555555"Output:
The phone number is invalid.
Solution Steps
- Initialize the Phone Number String: Accept or define the phone number to validate.
- Create a Regular Expression (Regex):
- Define a regular expression to match common phone number patterns.
- Validate the Phone Number:
- Use the
test()method to check if the phone number matches the regex pattern.
- Use the
- Display the Result: Output whether the phone number is valid or invalid.
JavaScript Program
// JavaScript Program to Validate a Phone Number
// Author: https://www.rameshfadatare.com/
function validatePhoneNumber(phoneNumber) {
// Step 2: Define the regular expression for validating phone numbers
const phonePattern = /^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/;
// Step 3: Test the phone number against the regex
if (phonePattern.test(phoneNumber)) {
console.log("The phone number is valid.");
} else {
console.log("The phone number is invalid.");
}
}
// Example usage
const phoneNumber = "123-456-7890";
validatePhoneNumber(phoneNumber);
Explanation
Step 1: Define the Regular Expression
The regular expression used in this program is:
/^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/This regex matches many common phone number formats:
^[+]*: Allows an optional+for country codes.[(]?\d{1,4}[)]?: Matches an optional area code enclosed in parentheses.[-\s./0-9]*: Matches digits along with optional separators like hyphens, spaces, periods, or slashes.
Step 2: Test the Phone Number
- The
test()method is used to check if the phone number matches the regex pattern. If it does, the phone number is valid; otherwise, it is invalid.
Output Example
The phone number is valid.
Example with Invalid Input
const phoneNumber = "5555555";
validatePhoneNumber(phoneNumber);
Output:
The phone number is invalid.
HTML Example with User Input
You can also validate a phone number using a form input in HTML and JavaScript.
HTML and JavaScript Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Phone Number Validator</title>
</head>
<body>
<h1>Phone Number Validator</h1>
<input type="text" id="phoneInput" placeholder="Enter your phone number">
<button onclick="validatePhoneNumber()">Validate</button>
<p id="result"></p>
<script>
function validatePhoneNumber() {
const phoneNumber = document.getElementById("phoneInput").value;
const phonePattern = /^[+]*[(]?\d{1,4}[)]?[-\s./0-9]*$/;
if (phonePattern.test(phoneNumber)) {
document.getElementById("result").textContent = "The phone number is valid.";
} else {
document.getElementById("result").textContent = "The phone number is invalid.";
}
}
</script>
</body>
</html>
Explanation of HTML Example
- The user enters a phone number in the input field, and when the "Validate" button is clicked, the
validatePhoneNumber()function is called to check if the phone number is valid. - The result is displayed in the
<p>element with theid="result".
Output in Browser
When the user enters a valid phone number, the message "The phone number is valid." will be displayed. If the phone number is invalid, the message "The phone number is invalid." will appear.
Conclusion
This JavaScript program validates a phone number using regular expressions. The program handles various formats of phone numbers, including those with country codes, spaces, hyphens, and parentheses. You can extend this program further by modifying the regular expression to handle specific country formats or more complex scenarios.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment