How to Validate Text Strings in Python
Validate strings with a reusable helper that checks type, length limits, and empty string handling.
Python code
33 linesdef is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
"""
Validate if a value is a string and meets length requirements.
Args:
value: The value to validate
min_length: Minimum allowed length (default 1)
max_length: Maximum allowed length (None = no limit)
allow_empty: If True, empty strings are valid
Returns:
bool: True if valid, False otherwise
"""
if not isinstance(value, str):
return False
if not allow_empty and len(value) == 0:
return False
if len(value) < min_length:
return False
if max_length is not None and len(value) > max_length:
return False
return True
def main():
test_values = ["hello", "", 123, "abc", "A" * 50]
for value in test_values:
result = is_valid_text(value, min_length=3, max_length=10)
print(f"Value: {value!r:55} -> Valid: {result}")
if __name__ == "__main__":
main()
Output
Value: 'hello' -> Valid: True
Value: '' -> Valid: False
Value: 123 -> Valid: False
Value: 'abc' -> Valid: True
Value: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' -> Valid: False
How it works
The function first checks isinstance(value, str) to reject non-string types like integers early. It then applies length rules: min_length sets a lower bound, max_length (when not None) sets an upper bound, and allow_empty controls whether zero-length strings pass. The checks are ordered to fail fast, avoiding redundant work when earlier validations fail. This pattern keeps inputs predictable before they reach other parts of your code.
Common mistakes
- Forgetting to check for non-string types before calling len()
- Not handling None as max_length, causing TypeError on comparison
- Assuming empty strings are always invalid when allow_empty is needed
- Using >= or <= instead of > and < for length boundaries
Variations
- Use str.strip() to validate non-whitespace text
- Add regex patterns (e.g., re.fullmatch) for format-specific validation
Real-world use cases
- Validating user-supplied form fields (e.g., names, passwords) before saving to a database.
- Checking environment variable values loaded as strings against expected length constraints.
- Sanitizing API payloads to ensure required text fields meet length rules before processing.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.