Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

validate phone number using regular expression

Here is my code:

def phone_number(number_input):
    """validate user input of phone number"""
while True:
    number_input = print(input("Please enter your phone number: "))
    if  re.search("\d{3}-\d{3}-\d{4}" ,number_input):
        print("You phone number is: " + number_input)
        break
    else:
        print("Please enter a valid phone number ex. 123-456-5678")


phone_number(number_input)

The code does not do the job of validation and I get the following error:

Traceback (most recent call last):
  File "C:\Users\ablev\eclipse-workspace\matrix\matrix.py", line 13, in <module>
    if  re.search("\d{3}-\d{3}-\d{4}" ,number_input):
  File "C:\Users\ablev\AppData\Local\Programs\Python\Python310\lib\re.py", line 200, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The print() function does not return anything. So you need to store input() first then print() if you want it.

Moreover your code, while working with the modification, does not make sense. So I modified to define a real function which return the phone number if valid.

import re

def phone_number():
    """validate user input of phone number"""
    while True:
        number_input = input("Please enter your phone number: ")
        print(number_input)
        if  re.search("\d{3}-\d{3}-\d{4}" ,number_input):
            print("You phone number is: " + number_input)
            return number_input
        else:
            print("Please enter a valid phone number ex. 123-456-5678")


number_input = phone_number()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading