Input Validation in 1 line

Input Validation in 1 line

Input validation is the process of checking if the input provided by the user or another external source meets the expectations of the program and is in the expected format.

Example: Code snippet is taken from the book “Automate the boring stuff with Python.”

→ Here we are checking if a user is entering an age in an integer or not, Age should not be negative or an alphabet.

# Input Validation Checker
while True:
    print('Enter your age:')
    age = input()
    try:
        age = int(age)
    except:
        print('Please use numeric digits.')
        continue
    if age < 1:
        print('Please enter a positive number.')
        continue
    break
print(f'Your age is {age}.')

Output:

Problem: If we are taking 10 inputs so we have to write 11 * 10 = 110 lines of code just for input validation.

Solution:
we can use pyinputplus.


Pyinputplus

pyinputplus is a Python library that provides a set of functions for input validation and error handling. It is built on top of the input() function and provides additional functionality such as:

  • Validation: You can use pyinputplus to validate user input by specifying the expected data type, the minimum and maximum values (if applicable), and a regular expression pattern (if desired).

  • Retries: You can specify the number of times the user should be prompted to enter the correct input before giving up.

  • Timeouts: You can specify a timeout for the input, after which the function will return None if no input has been provided.

  • Custom error messages: You can specify custom error messages to be displayed when the user enters invalid input.

For more information you can check the official website here:
https://pyinputplus.readthedocs.io/

Installation

pip install --user pyinputplus

Use

import pyinputplus as pyip

Example:

response = pyip.inputNum()
# 1 line to do everything that our code (11 lines of code doing)

Output:

Example 2:
Let’s try another example, let’s say we want the user to enter a number < 100 what we will do is:

while True:
    print("Enter a number: ")
    num = int(input())

    if num >= 100:
        print("Input must be less 100")
        continue
    break

print('Num entered is: ', num)

Output:

Using pyinputplus:

response = pyip.inputNum('Enter num: ', lessThan=100)

Output:

isn't that cool?

We can also say that the user should enter a number > 100.

# Likewise we can also use greaterThan
response = pyip.inputNum('Enter num: ', greaterThan=100)

Output:

# To get help
help(pyip.inputChoice)

→ For more you can visit https://pyinputplus.readthedocs.io/

Also, you can check the code here: https://github.com/umairmaratab/Input-Validation

Please comment if you would like anything to add or to improve.