import re
import json
def validate_form(form_data, schema):
"""
Validates form data against a JSON schema. Designed for non-production use.
Args:
form_data (dict): Dictionary representing the form data.
schema (dict): JSON schema defining expected data types and constraints.
Returns:
dict: A dictionary containing validation errors. Empty if no errors.
"""
errors = {}
for field, rules in schema.items():
value = form_data.get(field)
if value is None:
if 'required' in rules and rules['required']:
errors[field] = "Required field"
continue # Skip if not required
expected_type = rules.get('type')
if expected_type:
if expected_type == 'string':
if not isinstance(value, str):
errors[field] = f"Expected string, got {type(value).__name__}"
elif expected_type == 'integer':
if not isinstance(value, int):
try:
value = int(value) #Attempt conversion
except (ValueError, TypeError):
errors[field] = f"Expected integer, got {type(value).__name__}"
if value < rules.get('minimum'):
errors[field] = f"Must be at least {rules['minimum']}"
if value > rules.get('maximum'):
errors[field] = f"Must be at most {rules['maximum']}"
elif expected_type == 'number':
if not isinstance(value, (int, float)):
try:
value = float(value)
except (ValueError, TypeError):
errors[field] = f"Expected number, got {type(value).__name__}"
if value < rules.get('minimum'):
errors[field] = f"Must be at least {rules['minimum']}"
if value > rules.get('maximum'):
errors[field] = f"Must be at most {rules['maximum']}"
elif expected_type == 'boolean':
if not isinstance(value, bool):
errors[field] = f"Expected boolean, got {type(value).__name__}"
elif expected_type == 'email':
if not re.match(r"[^@]+@[^@]+\.[^@]+", value):
errors[field] = "Invalid email format"
elif expected_type == 'url':
if not re.match(r"https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)", value):
errors[field] = "Invalid URL format"
if 'minLength' in rules and isinstance(value, str) and len(value) < rules['minLength']:
errors[field] = f"Must be at least {rules['minLength']} characters"
if 'maxLength' in rules and isinstance(value, str) and len(value) > rules['maxLength']:
errors[field] = f"Must be at most {rules['maxLength']} characters"
if 'pattern' in rules and isinstance(value, str) and not re.match(rules['pattern'], value):
errors[field] = "Does not match required pattern"
return errors
if __name__ == '__main__':
# Example Usage
form_schema = {
"name": {"type": "string", "required": True, "minLength": 2, "maxLength": 50},
"email": {"type": "email", "required": True},
"age": {"type": "integer", "minimum": 0, "maximum": 120},
"is_active": {"type": "boolean"},
"url": {"type": "url"},
"description": {"type": "string"}
}
form_data1 = {
"name": "John",
"email": "john@example.com",
"age": 30,
"is_active": True,
"url": "https://www.example.com",
"description": "A
Add your comment