๐ Day 103/150 – Phone Number Validation in Python
Validating phone numbers is one of the most common tasks in Python applications. Whether you're building a registration form, login system, or contact management app, ensuring users enter a valid phone number helps improve data accuracy and prevents invalid entries.
In this post, we'll explore four different ways to validate phone numbers in Python, starting from simple checks to a more reliable solution using Regular Expressions.
Method 1 – Basic Phone Number Validation
Method 2 – Check Digits Only
A valid phone number should contain only numeric digits.
Sample Input
9876543210
Output
Valid Phone Number
Explanation
isdigit() checks whether every character in the string is a digit.
If all characters are numeric, it returns True.
Otherwise, the phone number is considered invalid.
Note: This method doesn't verify the length of the phone number.
Method 3 – Check Length and Digits
This method combines the previous two validations to make the check more reliable.
Sample Input
9876543210
Output
Valid Phone Number
Explanation
len(phone) == 10 ensures the phone number contains exactly 10 characters.
phone.isdigit() confirms every character is a digit.
Both conditions must be true for the phone number to be valid.
This approach is commonly used in beginner-level Python programs.
Method 4 – Using Regular Expressions
Regular Expressions (Regex) provide a more professional and flexible way to validate phone numbers.
Sample Input
9876543210
Output
Valid Phone Number
Explanation
import re imports Python's Regular Expression module.
^[0-9]{10}$ means:
^ → Start of the string
[0-9] → Any digit from 0 to 9
{10} → Exactly 10 digits
$ → End of the string
re.match() checks whether the entire input matches the pattern.
Regex is widely used in real-world applications because it provides accurate validation with minimal code.
Comparison of Methods
Method Best For
Check Length Basic validation
Check Digits Only Ensuring numeric input
Check Length + Digits Beginner-friendly phone validation
Regular Expressions Professional and production-level validation
๐ฅ Key Takeaways
Phone number validation helps prevent invalid user input.
len() checks whether the phone number has the required number of characters.
isdigit() ensures every character is numeric.
Combining length and digit validation provides a better solution.
Regular Expressions (re) offer the most reliable and scalable validation approach.
Phone number validation is commonly used in registration forms, authentication systems, contact applications, and web development projects.
Stay tuned for Day 104 of the #150DaysOfPython series! ๐
Learn :

0 Comments:
Post a Comment