I am trying to accept input of just phone numbers. The user is prompted to input a number. One method is to accept any input, and after the user has entered the input, check if it's a valid phone number. However, instead of checking the input after the user presses enter, I would like to check each input as the user is pressing each key. If the key is a number then it will be accepted. For instance if the user types 1234a, then the input will only accept and display 1234 and pressing a or any invalid key will not result in any behavior.
Asked
Active
Viewed 88 times
-1
-
1This would require a key listener of some sort, an easier solution may be to take user input and trim out any invalid characters (non-digits in this case) – Ewan Brown Dec 27 '21 at 04:01
-
I've never tried it myself, but this looks promising: [How to read a single character from the user?](/q/510357/4518341) – wjandrea Dec 27 '21 at 04:07
-
Please provide enough code so others can better understand or reproduce the problem. – Community Jan 04 '22 at 06:49
1 Answers
-1
I think this might help you. What it does is to take specific user input in the form of:
- Only digits
- Using the following pattern: XXX-XXX-XXXX.
This can obviously be crafted to specific number formats including country code and/or local number patterns according to your needs.
# import RegEx module
import re
def phone_checker(phone_number):
print("Enter phone number as XXX-XXX-XXXX")
while True:
pattern = r'\d{3}-\d{3}-\d{4}' #create a phone number pattern
res = re.findall(pattern,phone_number) #search for pattern in user input
to_string = ''.join(res) #convert to string
if phone_number in to_string:
print("Number accepted!")
break
else:
print("Number not recognized. Try again.")
phone_checker(phone_number=input("Enter phone number: "))

Robin Sage
- 969
- 1
- 8
- 24