exit
Authors Note: I am learning as I write this series so you might find mistakes. If you find them please comment, or if you know a better way, then please share it!
Introduction
Have you ever written a Python program that crashed because a user typed “twenty” instead of “20”? Or maybe your code broke when someone entered their email as “not-an-email”? Input validation is your shield against these common problems, and today you’re going to learn them!
Think of input validation as a security guard for your program. Just like a guard checks IDs at the door, input validation checks that user data is correct, safe, and in the expected format before your program processes it. For anyone building input forms, this is a necessary skill in order to write robust, user-friendly applications that won’t crash at the first sign of unexpected input.
In this comprehensive guide, we’ll explore powerful input validation functions that make your life easier, from basic string validation to complex date/time checking. You’ll discover how the PyInputPlus library transforms tedious validation code into simple, one-line solutions .
Why Input Validation Matters for Python Beginners
The Traditional Approach vs. Modern Solutions
Let’s compare how input validation looks with and without proper tools:
Traditional Approach (Tedious and Error-Prone):
while True:
= input("Enter your age: ")
age try:
= int(age)
age if age < 1:
print("Please enter a positive number.")
continue
break
except ValueError:
print("Please use numeric digits.")
Modern Approach with PyInputPlus (Clean and Simple):
import pyinputplus as pyip
= pyip.inputInt(prompt="Enter your age: ", min=1) age
The difference is striking! The modern approach handles all validation, error messages, and reprompting automatically .
Getting Started with PyInputPlus
Installation
Before we get into the functions, let’s install PyInputPlus:
pip install pyinputplus
Basic Import
import pyinputplus as pyip
Now you’re ready!
Complete Guide to Input Validation Functions
Let’s explore each input validation function with some practical examples.
1. inputStr() - Smart String Input
The inputStr()
function is like Python’s built-in input()
, but with validation superpowers.
Basic Usage:
= pyip.inputStr(prompt="Enter your name: ") name
Advanced Features:
# Minimum and maximum length
= pyip.inputStr(
username ="Create username (3-15 characters): ",
prompt=3,
minLength=15
maxLength
)
# Custom validation with regex
= pyip.inputStr(
phone ="Enter phone (digits only): ",
prompt=[r'^\d+$'] # Only digits allowed
allowRegexes )
2. inputInt() - Integer Input with Validation
Never worry about type conversion errors again!
Basic Usage:
= pyip.inputInt(prompt="Enter your age: ") age
With Range Validation:
# Age between 1 and 120
= pyip.inputInt(
age ="Enter age (1-120): ",
promptmin=1,
max=120
)
# Score with specific range
= pyip.inputInt(
score ="Enter test score (0-100): ",
promptmin=0,
max=100
)
3. inputFloat() - Decimal Number Input
Perfect for prices, measurements, and scientific data.
Example:
# Product price
= pyip.inputFloat(
price ="Enter price: $",
promptmin=0.01 # Minimum 1 cent
)
# Temperature reading
= pyip.inputFloat(
temp ="Enter temperature (°C): ",
promptmin=-273.15 # Absolute zero
)
4. inputChoice() - Restricted Choice Input
Ensure users only select from predefined options.
Example:
# Simple choice
= pyip.inputChoice(['small', 'medium', 'large'])
size
# With custom prompt
= pyip.inputChoice(
color 'red', 'green', 'blue'],
[="Choose a color (red/green/blue): "
prompt )
6. inputDatetime() - Date and Time Validation
Handle date/time input without complex parsing.
Example:
# Basic date input
= pyip.inputDatetime(prompt="Enter your birthday: ")
birthday
# With specific format
= pyip.inputDatetime(
appointment ="Enter date (MM/DD/YYYY): ",
prompt=['%m/%d/%Y']
formats )
7. inputYesNo() - Boolean Questions Made Easy
Perfect for confirmation prompts.
Example:
# Returns True for yes, False for no
= pyip.inputYesNo(prompt="Do you want to continue? ")
confirm
# Accepts: yes, y, no, n (case-insensitive)
if confirm:
print("Continuing...")
else:
print("Operation cancelled.")
8. inputBool() - True/False Input
For when you need explicit Boolean values.
Example:
# Accepts "True" or "False"
= pyip.inputBool(prompt="Enable debug mode? ") debug_mode
9. inputEmail() - Email Address Validation
Ensure valid email formats without regex headaches.
Example:
= pyip.inputEmail(prompt="Enter your email address: ")
email # Automatically validates format like [email protected]
10. inputFilepath() - File Path Validation
Check file paths and optionally verify existence.
Example:
# Just validate path format
= pyip.inputFilepath(prompt="Enter config file path: ")
config_path
# Ensure file exists
= pyip.inputFilepath(
data_file ="Enter data file: ",
prompt=True
mustExist )
11. inputPassword() - Secure Password Input
Hide password characters as users type.
Example:
= pyip.inputPassword(prompt="Enter password: ")
password # Characters are masked with * as user types
Comprehensive Comparison Table
Here’s a detailed comparison of all input validation functions:
Function | Purpose | Return Type | Example Input | Example Output | Key Features |
---|---|---|---|---|---|
inputStr() | Validated string input | str |
“Hello” | “Hello” | Length limits, regex patterns |
inputInt() | Integer validation | int |
“42” | 42 | Min/max values, greater/less than |
inputFloat() | Decimal validation | float |
“3.14” | 3.14 | Range checking, precision |
inputChoice() | Limited options | str |
“blue” | “blue” | Must match list items |
inputMenu() | Numbered menu | str |
“2” | “Option 2” | Auto-numbered display |
inputDatetime() | Date/time input | datetime |
“2024-01-01” | datetime object | Format flexibility |
inputYesNo() | Yes/no questions | bool |
“yes” | True | Accepts y/n variations |
inputBool() | Boolean input | bool |
“True” | True | Explicit True/False |
inputEmail() | Email validation | str |
“[email protected]” | “[email protected]” | Format checking |
inputFilepath() | Path validation | str |
“/home/file.txt” | “/home/file.txt” | Existence checking |
inputPassword() | Hidden input | str |
“secret123” | “secret123” | Character masking |
Advanced Features and Best Practices
1. Setting Timeouts and Retry Limits
Prevent infinite loops with smart limits:
# Timeout after 10 seconds
= pyip.inputStr(prompt="Quick! Enter your name: ", timeout=10)
response
# Limit to 3 attempts
= pyip.inputInt(prompt="Enter the answer: ", limit=3)
answer
# Combine both
= pyip.inputStr(prompt="Enter code: ", timeout=30, limit=5) data
2. Default Values
Provide fallbacks for better user experience:
# Default if user presses Enter
= pyip.inputStr(
name ="Enter name (or press Enter for 'Guest'): ",
prompt="Guest",
default=True
blank )
3. Custom Validation Functions
Create your own validation logic:
def validatePhone(text):
if len(text) != 10 or not text.isdigit():
raise Exception('Phone must be 10 digits')
return text
= pyip.inputCustom(validatePhone) phone
4. Error Handling
Gracefully handle validation failures:
try:
= pyip.inputInt(prompt="Age: ", limit=3)
age except pyip.RetryLimitException:
print("Too many invalid attempts!")
= 0 # Default value age
Security Best Practices
🔒 Security First: Input validation is your first line of defense against security vulnerabilities .
Important Security Guidelines
Never Trust User Input
- Always validate, even from “trusted” sources
- Assume all input is potentially malicious
Use Whitelisting Over Blacklisting
- Define what’s allowed, not what’s forbidden
- More secure and maintainable
Validate Early and Often
- Check input immediately upon receipt
- Re-validate before critical operations
Avoid Dangerous Functions
# NEVER DO THIS: = input("Enter code: ") user_code eval(user_code) # Extremely dangerous! # DO THIS INSTEAD: = pyip.inputChoice(['option1', 'option2']) choice
Sanitize for Context
- Different contexts require different validation
- File paths need different checks than usernames
Your Turn! Practical Exercise
Let’s put your new knowledge to the test with a real-world scenario!
Challenge: Create a user registration system that validates:
- Username (3-20 characters, alphanumeric only)
- Age (must be 13 or older)
- Email address
- Password (at least 8 characters)
- Terms acceptance (yes/no)
Try writing the code yourself before checking the solution!
Click here for Solution!
import pyinputplus as pyip
print("=== User Registration ===\n")
# Username validation
= pyip.inputStr(
username ="Username (3-20 chars, letters/numbers only): ",
prompt=3,
minLength=20,
maxLength=[r'^[a-zA-Z0-9]+$'],
allowRegexes=[r'[^a-zA-Z0-9]']
blockRegexes
)
# Age validation
= pyip.inputInt(
age ="Age: ",
promptmin=13,
=120
lessThan
)
# Email validation
= pyip.inputEmail(prompt="Email address: ")
email
# Password validation
= pyip.inputPassword(
password ="Password (min 8 characters): ",
prompt=8
minLength
)
# Terms acceptance
= pyip.inputYesNo(
accepted ="Do you accept the terms and conditions? "
prompt
)
if accepted:
print(f"\n✅ Registration successful!")
print(f"Welcome, {username}!")
else:
print("\n❌ Registration cancelled - terms not accepted.")
Quick Takeaways
- ✅ Input validation prevents crashes and security vulnerabilities in your Python programs
- ✅ PyInputPlus transforms complex validation into simple one-liners
- ✅ Always validate user input - never trust data from external sources
- ✅ Use the right function for each data type (inputInt for numbers, inputEmail for emails, etc.)
- ✅ Set appropriate limits with timeouts, retry limits, and value ranges
- ✅ Handle errors gracefully to improve user experience
- ✅ Whitelisting is more secure than blacklisting for input validation
- ✅ Custom validators let you implement complex business logic easily
Common Pitfalls to Avoid
1. Forgetting Edge Cases
# Bad: Doesn't handle negative numbers
= pyip.inputInt(prompt="Enter age: ")
age
# Good: Ensures positive age
= pyip.inputInt(prompt="Enter age: ", min=0) age
2. Over-Permissive Validation
# Bad: Too permissive
= pyip.inputStr(prompt="Password: ")
password
# Good: Enforces minimum security
= pyip.inputPassword(prompt="Password: ", minLength=8) password
3. Poor Error Messages
# Bad: Generic error
="Number: ")
pyip.inputInt(prompt
# Good: Helpful guidance
pyip.inputInt(="Enter a number between 1-10: ",
promptmin=1,
max=10
)
Conclusion
Congratulations! You’ve just mastered Python input validation, transforming yourself from a beginner who writes fragile code to a developer who creates robust applications. By using PyInputPlus and following the best practices we’ve covered, you’ll write programs that gracefully handle any input users throw at them .
Remember, input validation isn’t just about preventing errors; it’s about creating a professional user experience and protecting your application from security vulnerabilities. Every time you use inputInt()
instead of plain input()
, you’re making your code more reliable and your users happier.
Your Next Steps:
- Install PyInputPlus and try each function
- Refactor an existing project to use proper input validation
- Create a small project using at least 5 different validation functions
- Share your experience with other Python beginners!
Frequently Asked Questions (FAQs)
Q1: Do I always need to use PyInputPlus for input validation? A: While PyInputPlus makes validation much easier, you can write custom validation logic using loops and try-except blocks. However, for beginners and rapid development, PyInputPlus saves time and reduces errors.
Q2: Can I use PyInputPlus in web applications? A: PyInputPlus is designed for command-line applications. For web apps, use form validation libraries specific to your web framework (like Flask-WTF or Django forms).
Q3: What’s the difference between inputNum(), inputInt(), and inputFloat()? A: inputInt()
only accepts whole numbers (integers), inputFloat()
accepts decimal numbers, and inputNum()
accepts both integers and floats, returning the appropriate type.
Q4: How do I validate multiple conditions at once? A: You can combine PyInputPlus parameters or create custom validation functions. For complex logic, use inputCustom()
with your own validator.
Q5: Is input validation enough for security? A: Input validation is the first line of defense, but comprehensive security requires multiple layers including output encoding, secure communication, and proper authentication .
Join the Conversation!
Did this guide help you write better Python code? We’d love to hear about your experience with input validation! Share your favorite validation function or a creative way you’ve used PyInputPlus in the comments below.
Help others discover this guide:
- 🐦 Tweet your favorite tip with #PythonInputValidation #steveondata
- 💼 Share on LinkedIn to help fellow developers
- ⭐ Star the PyInputPlus repository on GitHub
References
Here are four working, relevant resources to deepen your understanding of Python input validation:
PyInputPlus Official Documentation
The comprehensive official documentation for PyInputPlus, featuring detailed explanations of all functions, parameters, and advanced usage examples. This is your go-to reference for mastering every feature discussed in this article.Automate the Boring Stuff with Python: Input Validation Chapter
A beginner-friendly chapter from Al Sweigart’s popular book (who also created PyInputPlus). This resource provides practical examples and explains input validation concepts in simple terms, perfect for Python beginners.Real Python: Python User Input Tutorial
An in-depth tutorial covering user input handling, validation techniques, and best practices. This resource goes beyond PyInputPlus to explore various approaches to input validation in Python applications.OWASP Input Validation Cheat Sheet
Essential security guidelines for input validation from the Open Web Application Security Project. While not Python-specific, these principles are crucial for writing secure code and understanding why proper validation matters.
Happy coding, and remember: validated input is happy input! 🐍✨
You can connect with me at any one of the below:
Telegram Channel here: https://t.me/steveondata
LinkedIn Network here: https://www.linkedin.com/in/spsanderson/
Mastadon Social here: https://mstdn.social/@stevensanderson
RStats Network here: https://rstats.me/@spsanderson
GitHub Network here: https://github.com/spsanderson
Bluesky Network here: https://bsky.app/profile/spsanderson.com
My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ
You.com Referral Link: https://you.com/join/EHSLDTL6