Nullable

The `Nullable` rule allows a field to be either null or valid according to other rules. It ensures flexibility in data validation.

The Nullable rule is designed to handle fields that can be either null or must satisfy additional validation criteria if not null. It is particularly useful for optional fields where, if a value is provided, it should adhere to specified rules. This rule helps in creating flexible validation logic, making it easier to manage data that may or may not be present.

from data_guard.validator import Validator
from data_guard.rules.nullable import Nullable

# Define the data to be validated
data = {"name": None, "email": "johndoe@example.com"}

# Define the validation rules
rules = {
    "name": ["string", "nullable"],
    "email": ["email"],
}

# Create a Validator instance
validator = Validator(data, rules)

# Perform the validation
response = validator.validate()

# Check if validation failed and print the errors if any
if response.validated:
    # Output: {"age": None, "email": "johndoe@example.com"}
    print("Validation passed!", response.data)
else:
    print("Validation failed with errors:", response.errors)

Overview

  • Purpose: Permits a field to be null but validates the field if it contains a value.

  • Checks: Allows null values and applies additional validation only when the field is not null.

  • Result: Validation passes if the field is null or if non-null values meet the specified criteria; otherwise, an error message is generated.

Last updated