1. import re
  2. import json
  3. def validate_form(form_data, schema):
  4. """
  5. Validates form data against a JSON schema. Designed for non-production use.
  6. Args:
  7. form_data (dict): Dictionary representing the form data.
  8. schema (dict): JSON schema defining expected data types and constraints.
  9. Returns:
  10. dict: A dictionary containing validation errors. Empty if no errors.
  11. """
  12. errors = {}
  13. for field, rules in schema.items():
  14. value = form_data.get(field)
  15. if value is None:
  16. if 'required' in rules and rules['required']:
  17. errors[field] = "Required field"
  18. continue # Skip if not required
  19. expected_type = rules.get('type')
  20. if expected_type:
  21. if expected_type == 'string':
  22. if not isinstance(value, str):
  23. errors[field] = f"Expected string, got {type(value).__name__}"
  24. elif expected_type == 'integer':
  25. if not isinstance(value, int):
  26. try:
  27. value = int(value) #Attempt conversion
  28. except (ValueError, TypeError):
  29. errors[field] = f"Expected integer, got {type(value).__name__}"
  30. if value < rules.get('minimum'):
  31. errors[field] = f"Must be at least {rules['minimum']}"
  32. if value > rules.get('maximum'):
  33. errors[field] = f"Must be at most {rules['maximum']}"
  34. elif expected_type == 'number':
  35. if not isinstance(value, (int, float)):
  36. try:
  37. value = float(value)
  38. except (ValueError, TypeError):
  39. errors[field] = f"Expected number, got {type(value).__name__}"
  40. if value < rules.get('minimum'):
  41. errors[field] = f"Must be at least {rules['minimum']}"
  42. if value > rules.get('maximum'):
  43. errors[field] = f"Must be at most {rules['maximum']}"
  44. elif expected_type == 'boolean':
  45. if not isinstance(value, bool):
  46. errors[field] = f"Expected boolean, got {type(value).__name__}"
  47. elif expected_type == 'email':
  48. if not re.match(r"[^@]+@[^@]+\.[^@]+", value):
  49. errors[field] = "Invalid email format"
  50. elif expected_type == 'url':
  51. 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):
  52. errors[field] = "Invalid URL format"
  53. if 'minLength' in rules and isinstance(value, str) and len(value) < rules['minLength']:
  54. errors[field] = f"Must be at least {rules['minLength']} characters"
  55. if 'maxLength' in rules and isinstance(value, str) and len(value) > rules['maxLength']:
  56. errors[field] = f"Must be at most {rules['maxLength']} characters"
  57. if 'pattern' in rules and isinstance(value, str) and not re.match(rules['pattern'], value):
  58. errors[field] = "Does not match required pattern"
  59. return errors
  60. if __name__ == '__main__':
  61. # Example Usage
  62. form_schema = {
  63. "name": {"type": "string", "required": True, "minLength": 2, "maxLength": 50},
  64. "email": {"type": "email", "required": True},
  65. "age": {"type": "integer", "minimum": 0, "maximum": 120},
  66. "is_active": {"type": "boolean"},
  67. "url": {"type": "url"},
  68. "description": {"type": "string"}
  69. }
  70. form_data1 = {
  71. "name": "John",
  72. "email": "john@example.com",
  73. "age": 30,
  74. "is_active": True,
  75. "url": "https://www.example.com",
  76. "description": "A

Add your comment