
Security News
Open Source Maintainers Feeling the Weight of the EU’s Cyber Resilience Act
The EU Cyber Resilience Act is prompting compliance requests that open source maintainers may not be obligated or equipped to handle.
A robust Python library for validating and sanitizing input data with predefined rules and filters
Version 0.0.5 - Enhanced security and stability improvements
Is an Alpha version, develop in progress, do not use it in production
pip install inputrules
Total | Last Month | Last Week |
---|---|---|
A robust Python library for validating and sanitizing input data from Forms, JSON, and HTTP Requests with predefined rules and filters.
from inputrules import InputRules
#JSON Example
data = {
"id":100,
"data": {
"name":" Alvaro ",
"lastname":" De Leon ",
"age":35,
"email": "asdasd",
"opt":"30",
"parms":[
10,20,30,40,50,60,70,80,90,100
],
"phones": {
"name":"Zaraza",
"home":"123456",
"cell":"123456"
}
}
}
#Example of list of options
options = ['10','20','30','40','50']
o = InputRules(data)
o.rules("id","required,integer")
o.rules("data.name","required,string","trim,upper")
o.rules("data.lastname","required,string","trim,lower")
o.rules("data.age","required,integer")
o.rules("data.phone","string")
o.rules("data.email","string","b64encode")
o.rules("data.opt","options",options=options)
o.rules("data.phones.name","required,string")
if o.verify():
print("Data is valid")
data = o.data()
print(data)
InputRules provides a powerful data validation system through the InputRules
class. This class allows you to validate input data in a structured way and apply filters automatically.
from inputrules import InputRules, check
# Example data
data = {
"id": 100,
"name": " John ",
"email": "john@example.com",
"age": 25,
"status": "active"
}
# Create InputRules instance
validator = InputRules(data)
# Define validation rules
validator.rules("id", "required,integer")
validator.rules("name", "required,string", "trim,upper")
validator.rules("email", "required,mail")
validator.rules("age", "required,integer")
validator.rules("status", "required,options", options=["active", "inactive"])
# Validate data
if validator.verify():
print("Data is valid")
validated_data = validator.data()
print(validated_data)
else:
print("Errors found:")
for error in validator.errors():
print(f"- {error}")
required
: Field is requiredstring
: Must be a stringinteger
: Must be an integerfloat
: Must be a decimal numbernumeric
: Must be a number (integer or decimal)empty
: Must be empty!empty
: Must not be emptynone
: Must be None!none
: Must not be Nonemail
: Must be a valid email addressdomain
: Must be a valid domainip
: Must be a valid IP addressuuid
: Must be a valid UUIDoptions
: Must be in a list of valid optionsFilters are automatically applied to data after validation:
trim
or strip
: Removes whitespace from beginning and endlower
: Converts to lowercaseupper
: Converts to uppercaseucfirst
: First letter uppercaseucwords
: First letter of each word uppercaseint
or integer
: Converts to integerfloat
: Converts to decimalstr
or string
: Converts to stringbase64
or b64encode
: Encodes in base64b64decode
: Decodes from base64md5
: Generates MD5 hashurlencode
: Encodes for URLurldecode
: Decodes from URLxss
or escape
: Escapes HTML characterssql
: Sanitizes SQL input (removes dangerous SQL injection patterns)htmlentities
: Converts characters to HTML entitieshtmlspecialchars
: Converts special characters to HTML entitiesstriptags
: Removes HTML tagsaddslashes
: Escapes quotes and backslashesstripslashes
: Removes backslashesnl2br
: Converts line breaks to <br>
br2nl
: Converts <br>
to line breaksjson
: Converts to JSONNote: The serialize
and unserialize
filters have been removed for security reasons.
InputRules
supports validation of nested data structures using dot notation:
data = {
"user": {
"profile": {
"name": " Maria ",
"email": "maria@example.com",
"age": 30
},
"settings": {
"theme": "dark",
"notifications": True
}
}
}
validator = InputRules(data)
# Validate nested fields
validator.rules("user.profile.name", "required,string", "trim,ucfirst")
validator.rules("user.profile.email", "required,mail")
validator.rules("user.profile.age", "required,integer")
validator.rules("user.settings.theme", "required,options", options=["light", "dark"])
validator.rules("user.settings.notifications", "required")
if validator.verify():
validated_data = validator.data()
print(validated_data)
from inputrules import InputRules
# Form data
form_data = {
"username": " admin ",
"password": "123456",
"email": "admin@example.com",
"role": "admin",
"profile": {
"first_name": " john ",
"last_name": " doe ",
"age": 35,
"country": "US"
}
}
# Valid options
role_options = ["admin", "user", "moderator"]
country_options = ["US", "CA", "UK", "DE", "FR"]
# Create validator
validator = InputRules(form_data)
# Define rules
validator.rules("username", "required,string", "trim,lower")
validator.rules("password", "required,string", "md5")
validator.rules("email", "required,mail")
validator.rules("role", "required,options", options=role_options)
validator.rules("profile.first_name", "required,string", "trim,ucfirst")
validator.rules("profile.last_name", "required,string", "trim,ucfirst")
validator.rules("profile.age", "required,integer")
validator.rules("profile.country", "required,options", options=country_options)
# Validate
if validator.verify():
print("✓ Valid data")
clean_data = validator.data()
print("Processed data:", clean_data)
else:
print("✗ Validation errors:")
for error in validator.errors():
print(f" - {error}")
The check
class provides static methods for validating individual values. It's useful for specific validations without needing to create a complete schema.
from inputrules import check
# Validate if it's a string
check.string("text") # True
check.string(123) # False
# Validate if it's an integer
check.integer(42) # True
check.integer(3.14) # False
# Validate if it's a decimal
check.float(3.14) # True
check.float(42) # False
# Validate if it's numeric (integer or decimal)
check.numeric(42) # True
check.numeric(3.14) # True
check.numeric("text") # False
# Validate if it's empty
check.empty("") # True
check.empty(None) # True
check.empty(0) # True
check.empty("text") # False
# Validate if it's None
check.none(None) # True
check.none("") # False
# Validate if it's NOT None
check.notnone("text") # True
check.notnone(None) # False
# Validate email
check.mail("user@example.com") # True
check.mail("invalid-email") # False
# Validate domain
check.domain("example.com") # True
check.domain("invalid..domain") # False
# Validate IP
check.ip("192.168.1.1") # True
check.ip("999.999.999.999") # False
# Validate UUID
check.uuid("123e4567-e89b-12d3-a456-426614174000") # True
check.uuid("invalid-uuid") # False
# Validate if it's in a list of options
options = ["red", "green", "blue"]
check.options("red", options) # True
check.options("yellow", options) # False
# Use multiple rules separated by commas
check.rules("john@example.com", "required,mail") # True
check.rules("", "required,string") # False
check.rules(25, "required,integer") # True
check.rules("test", "required,string,!empty") # True
# Sanitize SQL input
user_input = "'; DROP TABLE users; --"
safe_input = check.sanitize_sql(user_input)
print(safe_input) # " DROP TABLE users "
from inputrules import check
def validate_registration(form_data):
errors = []
# Validate username
if not check.rules(form_data.get('username'), 'required,string,!empty'):
errors.append("Username is required and must be valid")
# Validate email
if not check.rules(form_data.get('email'), 'required,mail'):
errors.append("Email must be a valid address")
# Validate age
if not check.rules(form_data.get('age'), 'required,integer'):
errors.append("Age must be an integer")
# Validate role
valid_roles = ['admin', 'user', 'moderator']
if not check.options(form_data.get('role'), valid_roles):
errors.append("Role must be admin, user or moderator")
return len(errors) == 0, errors
# Usage
form_data = {
'username': 'john_doe',
'email': 'john@example.com',
'age': 28,
'role': 'user'
}
is_valid, errors = validate_registration(form_data)
if is_valid:
print("Valid form")
else:
print("Errors:", errors)
from inputrules import check
def validate_config(config):
"""Validates system configuration"""
# Validate database host
if not check.rules(config.get('db_host'), 'required,string,!empty'):
return False, "Database host is required"
# Validate port
port = config.get('db_port')
if not check.integer(port) or port <= 0 or port > 65535:
return False, "Port must be an integer between 1 and 65535"
# Validate admin email
admin_email = config.get('admin_email')
if not check.mail(admin_email):
return False, "Admin email is not valid"
# Validate log level
log_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR']
if not check.options(config.get('log_level'), log_levels):
return False, "Log level must be DEBUG, INFO, WARNING or ERROR"
return True, "Valid configuration"
# Usage
config = {
'db_host': 'localhost',
'db_port': 3306,
'admin_email': 'admin@company.com',
'log_level': 'INFO'
}
is_valid, message = validate_config(config)
print(message)
from inputrules import InputRules, check
# User data
user_data = {
'name': ' John Doe ',
'email': 'john@example.com',
'age': 30,
'status': 'active'
}
# Validate data
validator = InputRules(user_data)
validator.rules("name", "required,string", "trim,ucfirst")
validator.rules("email", "required,mail")
validator.rules("age", "required,integer")
validator.rules("status", "required,options", options=["active", "inactive"])
if validator.verify():
# Valid data, process it
clean_data = validator.data()
print(f"Validated data: {clean_data}")
else:
print("Validation errors:")
for error in validator.errors():
print(f"- {error}")
serialize
/unserialize
filters: These filters used Python's pickle
module which could execute arbitrary code with untrusted inputsql
filter now removes more dangerous patterns including:
addslashes
filter: Now properly escapes single quotes, double quotes, and backslashesurlencode
filter: Removed double encoding issueThe empty()
function now correctly handles all data types:
False
is considered a valid value, not emptyInputRules
instance now has independent variablesgetValue()
function: Now returns None
instead of raising exceptionsThis documentation provides a complete guide for using both InputRules
and the check
class, allowing you to validate and sanitize data robustly and securely.
FAQs
A robust Python library for validating and sanitizing input data with predefined rules and filters
We found that inputrules demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The EU Cyber Resilience Act is prompting compliance requests that open source maintainers may not be obligated or equipped to handle.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.