In this article, I'll be covering how to validate user inputs in python using PyInputPlus.
Input validation is checking whether the value given by the user is of the correct format i.e if an email is to be provided by the user then the code should not accept anything other than an email. Improper input validation will cause bugs and vulnerabilities in the system.
PyInputPlus is a python module created by AI Sweigart that takes user input and checks whether it is valid. If invalid input is provided, it will keep on asking for input until a valid input is given.PyInputplus has functions such as inputStr(), inputInt(), InputDate() among others which are used in validating user input.
To install the module type the command below in your terminal:
pip install --user pyinputplus
To use it in your code add the following at the beginning of your code:
import pyinputplus as pyip
Pyinputplus is a long name hence we use pyip to save us time.
This function only accepts integers and floating-point numbers from the user.
>>> import pyinputplus as pyip >>> result = pyip.inputNum() who 'who' is not a number. 22 >>> result 22
>>> result = pyip.inputNum() 22.4 >>> result 22.4
From the snippets above you can see that 'who' is rejected because it is a string while 22.4 and 22 are accepted since they are floating-point values and integers respectively.
This function only accepts integer values and will reject floating-point values and strings.
>>> import pyinputplus as pyip >>> result = pyip.inputInt() mike 'mike' is not an integer. 22.4 '22.4' is not an integer. 30 >>> result 30
From the snippet above 'mike' will be rejected because it is a string and '22.4' will be rejected because it is a floating-point value.
This function is similar to the input() function but has features of PyInputPlus functions.
>>> import pyinputplus as pyip >>> result = pyip.inputStr() 34 >>> result '34' >>> result = pyip.inputStr() mike >>> result 'mike' >>> result = pyip.inputStr() 22.4 >>> result '22.4'
In the snippet above you see that integers, strings, and floats are accepted as inputs but are returned as strings.
This function gives users a list of choices from which to choose and only accepts one of the choices.
>>> import pyinputplus as pyip >>> result = pyip.inputChoice(['bee','dog','sheep']) Please select one of: bee, dog, sheep mike 'mike' is not a valid choice. Please select one of: bee, dog, sheep 12 '12' is not a valid choice. Please select one of: bee, dog, sheep dog >>> result 'dog'
From the snippet above 'mike' and '12' are rejected because they are not in the list provided as an argument. You can provide a list or a tuple as an argument in the function.
It works the same as the inputChoice function but provides a menu that is numbered from which the user should choose.
>>> import pyinputplus as pyip >>> result = pyip.inputMenu(['bee','dog','sheep']) Please select one of the following: * bee * dog * sheep cow 'cow' is not a valid choice. Please select one of the following: * bee * dog * sheep 12 '12' is not a valid choice. Please select one of the following: * bee * dog * sheep bee >>> result 'bee'
In the snippet above a menu is provided to the user from which they should choose one item from it.'12' and 'cow' is rejected because they are not in the list provided while 'dog' is accepted as the input.
>>> result = pyip.inputMenu(['bee','dog','sheep'], numbered=True) Please select one of the following: 1. bee 2. dog 3. sheep 2 >>> result 'dog'
Setting the numbered parameter to true numbers the menu items and you can choose an item by giving the corresponding number. A tuple can also be provided as an argument instead of a list.
These functions ensure the user only provides an input which is a date, time, or both.
>>> import pyinputplus as pyip >>> result = pyip.inputTime() 12 '12' is not a valid time. ss 'ss' is not a valid time. 12:00 >>> str(result) '12:00:00'
In the above snippet the inputTime() function only accepts time in the format hours, minutes then seconds separated by colons. The input into the str() function to change it to a string.'12' and 'ss' are rejected since they are not in the correct format.
>>> result = pyip.inputDate() 12121212 '12121212' is not a valid date. ww 'ww' is not a valid date. 12/12/2020 >>> str(result) '2020-12-12'
In the above snippet only dates in the format day,month, year separated by forwarding slashes are accepted as valid user inputs.
>>> result = pyip.inputDatetime() 12:00 12/12/2020 '12:00 12/12/2020' is not a valid date and time. 12/12/2020 '12/12/2020' is not a valid date and time. 12:00 '12:00' is not a valid date and time. 12/12/2020 12:00 >>> str(result) '2020-12-12 12:00:00'
From the snippet above the only accepted user input is date followed by time, reversing it, the input will be rejected. Date alone or time alone will be rejected.
This function only accepts floating-point values as the only valid user input.
In this function, as the user provides an input, * characters will be displayed to ensure sensitive information such as passwords is not displayed on the screen.
In this funtion only Yes and No accepted as valid input.
In this function True or False is the only accepted user input.
It ensures that only a file path and filename are entered by the user.
This function accepts only valid email addresses as user input.
Using this function you can create your validation logic by passing a function as an argument to this function.
It helps you get more information on other pyinputplus functions. You pass the function's name as an argument.
These parameters are used in inputNum() , inputInt() , and inputFloat() functions.They help you to specify the range os accepted user input values.
A text to be displayed before prompting the user for an input.
>>> import pyinputplus as pyip >>> response = pyip.inputInt(prompt='Enter your age:') Enter your age:23 >>> response 23
When set to True, the user does not need to enter anything as the input. By default, the blank parameter is set to False.
The limit parameter specified the number of tries a user is given to enter an input after which it raises a pyinputplus.RetryLimitException exception if the number of limits has been exceeded and no valid input is given.
>>> import pyinputplus as pyip >>> response = pyip.inputInt(limit=3) rr 'rr' is not an integer. rr 'rr' is not an integer. rr 'rr' is not an integer. Traceback (most recent call last): --snip--- raise limitOrTimeoutException pyinputplus.RetryLimitException
The timeout parameter specifies how many seconds to wait for a user inpt before raising a pyinputplus.TimeoutException exception.
>>> import pyinputplus as pyip >>> response = pyip.inputInt(timeout=5) 23 Traceback (most recent call last): File "<stdin>", line 1, in <module> --snip-- raise TimeoutException() pyinputplus.TimeoutException
When you pass a value to the default parameter, the value will be returned instead of raising an exception.
AllowRegexes parameter takes a regular expression that specifies what input is to be allowed. Blockregexes parameter takes a regex that specifies what user input should not be accepted. The parameter can take a list of regexes.
>>> result = pyip.inputStr(allowRegexes=[r'^fo.*'])
>>> result = pyip.inputStr(blockRegexes=[r'.*s$'])
Apart from the functions and parameters listed above, others can be found in the official documentation.
As seen PyInputPlus makes the work of validating user input very simple and easy.
Thanks for reading.