DEV Community

Dominic Koech
Dominic Koech

Posted on • Updated on

Python Input Validation Using PyInputPlus Module

In this article, I'll be covering how to validate user inputs in python using PyInputPlus.

Introduction

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.

Installation

To install the module type the command below in your terminal:

pip install --user pyinputplus
Enter fullscreen mode Exit fullscreen mode

To use it in your code add the following at the beginning of your code:

import pyinputplus as pyip
Enter fullscreen mode Exit fullscreen mode

Pyinputplus is a long name hence we use pyip to save us time.

Functions in PyInputPlus

1. inputNum()

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
Enter fullscreen mode Exit fullscreen mode
>>> result = pyip.inputNum()
22.4
>>> result
22.4
Enter fullscreen mode Exit fullscreen mode

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.

2. inputInt()

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
Enter fullscreen mode Exit fullscreen mode

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.

3. inputStr()

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'
Enter fullscreen mode Exit fullscreen mode

In the snippet above you see that integers, strings, and floats are accepted as inputs but are returned as strings.

4. inputChoice()

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'
Enter fullscreen mode Exit fullscreen mode

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.

5. inputMenu()

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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.

6. inputDatetime(), inputDate() and inputTime()

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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.

7. inputFloat()

This function only accepts floating-point values as the only valid user input.

8. inputPassword()

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.

9. inputYesNo()

In this funtion only Yes and No accepted as valid input.

10. inputBool()

In this function True or False is the only accepted user input.

11. inputFilepath()

It ensures that only a file path and filename are entered by the user.

12. inputEmail()

This function accepts only valid email addresses as user input.

13. inputCustom()

Using this function you can create your validation logic by passing a function as an argument to this function.

14. help()

It helps you get more information on other pyinputplus functions. You pass the function's name as an argument.

Common parameters PyInputPlus funtions

min/max/greaterThan/lessThan parameters

These parameters are used in inputNum() , inputInt() , and inputFloat() functions.They help you to specify the range os accepted user input values.

prompt parameter

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
Enter fullscreen mode Exit fullscreen mode

blank parameter

When set to True, the user does not need to enter anything as the input. By default, the blank parameter is set to False.

limit, timeout, and default parameters

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

When you pass a value to the default parameter, the value will be returned instead of raising an exception.

allowRegexes and blockRegexes parameters

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.*'])
Enter fullscreen mode Exit fullscreen mode
>>> result = pyip.inputStr(blockRegexes=[r'.*s$'])
Enter fullscreen mode Exit fullscreen mode

Conclusion

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.

Top comments (2)

Collapse
 
csfan profile image
Vivek Ramachandran

Thanks for the detailed explanation!
Could you please tell me what font are you using?! It is awesome!

Collapse
 
dominickoech profile image
Dominic Koech

Thank you :).
I use sans serif.