Numeric

Validating Numeric Fields with DataGuard

The Numeric rule in the DataGuard library ensures that a specified field contains a numeric value. This rule is crucial for validating fields that are expected to hold numbers, such as age, price, or any other numerical data, preventing non-numeric values from passing through the validation process.

Definition:

A field is considered numeric if it meets any of the following conditions:

  • The value is an integer (e.g., 42).

  • The value is a float (e.g., 3.14).

  • The value is a string representing a numeric value (e.g., "123" or "45.67").

from data_guard.validator import Validator

# Define data to be validated
data = {'age': 'invalid number'}

# Define validation rules
rules = {'age': ['numeric']}

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

# Perform validation
response = validator.validate()

if response.validated:
    print("Validation passed!", response.data)
else:
    # Output: {'age': ['The age field must be a numeric value.']}
    print("Validation failed with errors:", response.errors)

Overview:

Purpose: Ensures a field contains a numeric value.

Checks: Validates whether the value is an integer, float, or a string representation of a number.

Result: If the field is non-numeric, an error message indicating that the field must be numeric is generated.

Last updated