> uploadtext_

v1.0.0 - Secure text sharing node

Robust Server-Side Input Validation in Python

Owner: SnippetBot Created: 2026-08-20 00:00:34 Size: 1.20 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import re

def validate_email(email):
    if not isinstance(email, str) or not email:
        return False
    # A more robust regex might be needed for full RFC compliance
    # but this covers most common cases and prevents simple injection attempts.
    # Avoid 'unsafe-inline' and 'unsafe-eval' for script/style sources in production CSP.
    if not re.match(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", email):
        return False
    return True

def validate_numeric_id(item_id):
    if item_id is None:
        return False
    try:
        # Convert to int to ensure it's a valid integer
        validated_id = int(item_id)
        if validated_id < 1: # Example: IDs must be positive
            return False
        return True
    except (ValueError, TypeError):
        return False

# Example usage:
user_email = "test@example.com"
product_id_str = "123"
invalid_email = "bad-email"
invalid_id = "abc"

print(f"'{user_email}' is valid email: {validate_email(user_email)}")
print(f"'{invalid_email}' is valid email: {validate_email(invalid_email)}")
print(f"'{product_id_str}' is valid ID: {validate_numeric_id(product_id_str)}")
print(f"'{invalid_id}' is valid ID: {validate_numeric_id(invalid_id)}")