Data Validation Patterns
Error Collection
Collecting all validation errors lets a caller see every problem in one pass.
Error Collection
errors.py
def validate_order(quantity, price):
errors = []
if quantity <= 0:
errors.append("quantity")
if price <= 0:
errors.append("price")
return errors
price =
errors = validate_order(2, price)
print("errors=" + ",".join(errors) if errors else "errors=none")
def validate_order(quantity, price):
errors = []
if quantity <= 0:
errors.append("quantity")
if price <= 0:
errors.append("price")
return errors
price =
errors = validate_order(2, price)
print("errors=" + ",".join(errors) if errors else "errors=none")
error collection
Instead of stopping at the first invalid field, collect each error message into a list.