Custom Validation Rule

Extend DataGuard with your own validation logic to handle unique requirements, making the library adaptable to any data validation scenario.

Creating custom rules with DataGuard allows you to tailor the library to your application's unique validation needs. For instance, you might want to ensure that an age value falls within a specified range. DataGuard already includes a Between rule for this purpose, showcasing how the library can be easily customized to handle various validation scenarios.

To quickly create a new rule, you can use our command-line tool. Simply create a create_rule.py file with the following content:

from data_guard.libs.rule_creator import RuleCreator

def main():
    creator = RuleCreator(directory_name="rules")
    creator.create()

if __name__ == "__main__":
    main()

Usage:

python create_rule.py <rule_name_in_snake_case>

Example:

python create_rule.py between

Output:

This command will generate a between.py file in the rules directory.

from data_guard.rule import Rule

class Between(Rule):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def validate(self) -> bool:
        # Implement your validation logic here
        return True

    def get_message(self) -> str:
        # Provide a default message or leave it empty
        return ""

After creating your new rule, you can customize its logic to fit your requirements. Here's an example implementation of a 'between' rule:

from data_guard.rule import Rule

class Between(Rule):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    def validate(self) -> bool:
        # Validate parameter count and raise an exception if invalid.
        self.require_params_count(2)
        
        # Set parameters for custom messages.
        self.set_params({"small_value": self.args[0], "large_value": self.args[1]})

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

        # Output: {'age': 15}
        print(self.data)

        # Validation logic
        small_value = self.params.get("small_value")
        large_value = self.params.get("large_value")
        value = self.params.get("value")

        return large_value >= value >= small_value

    def get_message(self) -> str:
        return "The {field} field must be between {small_value} and {large_value}."
from data_guard.validator import Validator
from custom_rules.between import Between

# Define the data to be validated
data = {"age": 15}

# Define validation rules, including the custom Unique rule
rules = {"age": ["numeric", Between(18, 35)]}

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

# Perform validation
response = validator.validate()

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

Overview

Purpose: To create custom validation logic, such as range checks, ensuring data meets specific requirements.

Flexibility: Easily integrate custom rules like Between into the validation flow to handle diverse data scenarios.

Error Handling: Provide clear, custom error messages that accurately reflect validation outcomes, enhancing user feedback.

Last updated