How to Validate Text Strings in Python

Validate strings with a reusable helper that checks type, length limits, and empty string handling.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

33 lines
Python 3.9+
def 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

stdout
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

  1. Use str.strip() to validate non-whitespace text
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.