Python Forum

Full Version: How to verify the give number is valid
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I am trying to verify the given number is a valid phone number or not.

Conditions:
1. The number may be a 10 digit one : 9898989876
2. The number can start with "zero" : 09898989876
3. The number can be international : +919898989876

I use below program, and when I enter any of the above number my output is showing "Invalid number"

import re
mblNum =input("Please enter the mobile number to validate\n")
m = re.fullmatch('[+91]*[0]*[6-9]\d{9}', mblNum)
if m != None:
    print("valid number")
else:
    print("Invalid number")
This is a good source for how re works.
https://docs.python.org/3/library/re.html
Although this was set to solved, I'm going to post the solution I came up with. It's by far not the best as I've not really got into regrex yet. Hope it will help in the future.
#! /usr/bin/python3

import re
while True:
    num = input('Enter phone number: ')

    if len(num) < 10:
        print('Your number is too short')
    elif len(num) > 13:
        print('Your number is too long')
    else:
        match = re.findall(r'\d', num)

        if match:
            print('valid number')
        else:
            print('Invalid number')
        break
Regular expression you have matches all the three phone numbers

>>> mblNum =input("Please enter the mobile number to validate\n")
Please enter the mobile number to validate
9898989876
>>> m = re.fullmatch('[+91]*[0]*[6-9]\d{9}', mblNum)
>>> if m != None:
...     print("valid number")
... else:
...     print("Invalid number")
...
valid number