user2232448
user2232448

Reputation: 1

Validation for number length and digits

a=input('hello enter something ')

def checkingInput():
    if 0 <= int(a) <= 9:
        return a
    else:
        print('Invalid input!')

checkingInput()

I need a validation that it checks the input to see if the number entered is the correct length which should be 10 and only contains the digits 0 to 9.

Upvotes: 0

Views: 5209

Answers (1)

user1467267
user1467267

Reputation:

isDigit() checks if it's a integer. len() checks the length to compare.

if a.isdigit():
     print("It's a digit!")
else:
     print("It's not a digit!")

if len(a) == 10:
    print("It's exactly 10 digits long") // digits might also mean "characters"!
else:
    print("It's not exactly 10 digits long") // digits might also mean "characters"!

isDigit() is kind of unsafe tho. It ignores;

  • hexadecimals
  • decimals
  • negative numbers

If you want to be sure you might need to use regular expressions and see if the match is full digit. Something like this;

/\A\d{10}\Z/

This would also instantly check your length. If you just want to check for digit, then use;

/\A\d+\Z/

Upvotes: 4

Related Questions