Custom Error Messages

Tailor validation error messages to your needs, providing clear and specific feedback for various validation scenarios, ensuring better user guidance and experience.

The PyDataValidator library provides a powerful feature for customizing error messages, allowing you to deliver clear and context-specific feedback to users. This feature lets you define field-specific error messages, ensuring your validation logic is both robust and user-friendly. By specifying custom messages, you can improve the clarity and relevance of validation errors, enhancing the overall user experience.

from data_guard.validator import Validator

# Data to validate
data = {"name": None}

# Validation rules
rules = {"name": ["required"]}

# Custom error messages
messages = {"name.required": "{field} is required."}

# Initialize the validator
validator = Validator(data, rules, messages)

# Perform validation
response = validator.validate()

# Check if validation passed or failed
if response.validated:
    print("Validation passed!", response.data)
else:
    print(response.errors)  # Output: {"name": ["name is required"]}
# each rule has its own parameters like field, value and many others.
# for above example, the parameters will be: {'field': 'name', 'value': None}
# you can also use get_params method to get rules params for given field.
from data_guard.validator import Validator

# Data to validate
data = {"age": 15}

# Validation rules
rules = {"age": ["between:18,35"]}

# Custom error messages
params = validator.get_params("age", "between") # pass field and rule as args

# Output: {'field': 'age', 'value': 15, 'small_value': '18', 'large_value': '35'}
print(params)

messages = {
    "age.between": "The {field} field must be between {small_value} and {large_value}."
}

# Initialize the validator
validator = Validator(data, rules, messages)

# Perform validation
response = validator.validate()

# Check if validation passed or failed
if response.validated:
    print("Validation passed!", response.data)
else:
    # Output: {'age': ['The age field must be between 18 and 35.']}
    print(response.errors)

Overview:

  • Custom Messages: Define specific error messages for each field.

  • Dynamic Placeholders: Use {field} to dynamically insert the field name into the error message.

  • User-Friendly: Ensure validation errors are clear, descriptive, and consistent with your application’s tone.

Last updated