Skip to main content

validate

Validates data against validation rules. Supports two modes: rich validation with rule files (recommended) and legacy single-rule mode (backward compatible).

Rich Validation with Rule Files​

Use YAML/JSON rule files for comprehensive, reusable validation:

# Validate with rule file
undatum validate data.csv --rules validation-rules.yml
undatum validate workbook.xlsx --table Sheet2 --rules validation-rules.yml
undatum validate nested.jsonl --rules rules.yml --flatten-nested
undatum validate data.csv --rules rules.yml --filter '`status` == "active"'

# Filter by severity
undatum validate data.jsonl --rules rules.yml --severity error

# JSON output for CI/CD integration
undatum validate data.csv --rules rules.yml --format-out json

# Generate detailed violation report
undatum validate data.jsonl --rules rules.yml --violation-report violations.json

# Treat warnings as errors
undatum validate data.csv --rules rules.yml --fail-on-warnings

Rule File Format:

Rule files support field-level and cross-field validation with severity levels. Built-in formats (country, currency, language, date, phone, iban, uuid, pattern, ...), unique, and references to another file are listed on Validation rules and by undatum validate --list-rules. -O jsonl prints one violation per line.

rules:
# Field-level rules
- field: email
name: Email Required
description: Email field must be present
required: true
type: string
format: email
severity: error

- field: age
name: Age Range
description: Age must be between 0 and 120
type: number
min: 0
max: 120
severity: warning

- field: status
name: Status Values
type: string
enum: [active, inactive, pending]
severity: error

# Cross-field validation
- type: cross-field
name: Date Range Validation
description: End date must be after start date
condition: "end_date >= start_date"
fields: [start_date, end_date]
severity: error

Rule Types:

  • Required: required: true - Field must be present and non-empty
  • Type: type: string|number|integer|float|boolean - Value type validation
  • Format: format: email|url|uuid - Format validation
  • Range: min, max for numbers; min_length, max_length for strings
  • Enum: enum: [value1, value2, ...] - Whitelist validation
  • Pattern: pattern: 'regex' - Regular expression validation
  • Custom: custom: 'rule_name' - Use custom validation function from VALIDATION_RULEMAP
  • Cross-field: type: cross-field with condition expression

Severity Levels:

  • error: Hard errors that should block processing
  • warning: Soft warnings that don't block processing
  • info: Informational violations

Violation Reporting:

The validation command provides comprehensive reporting:

  • Summary statistics: Total violations by severity, by field, by rule
  • Detailed violations: Record-level violation details with context
  • JSON output: Machine-readable format for CI/CD integration
  • Violation report file: Detailed JSON report with all violations

Example Rule Files:

Example rule files are available in examples/validation-rules/:

  • basic-validation.yml - Common field-level validation rules
  • cross-field-validation.yml - Cross-field validation examples
  • complex-validation.yml - Comprehensive validation scenario

Engines:

  • For CSV and TSV files, --engine auto (the default) checks a rule file as one DuckDB query, about 4× faster on large files (1M rows: 1.4 s instead of 5.8 s).
  • It reports the same violations, in the same order and with the same messages, as the Python engine, which --engine python selects.
  • It applies to field rules made of required, type, references, unique, min/max, min_length/max_length, enum and pattern.
  • The file is checked record by record in Python when:
    • a rule uses format or custom, or is a cross-field rule;
    • a pattern uses \w, \s, \b or a construct DuckDB's regular expressions lack (Python reads them differently);
    • a value is a number only Python reads (digits or spaces outside ASCII);
    • the --filter has no SQL form;
    • the input is not CSV or TSV.
  • undatum quality --rules uses the same query.

Data Contracts (ODCS)​

--rules also takes an Open Data Contract Standard (ODCS v3) contract, a YAML file with kind: DataContract. undatum schema --format odcs writes a draft contract for a file:

undatum schema data.csv --format odcs --output contract.odcs.yaml
undatum validate data.csv --rules contract.odcs.yaml
undatum validate data.csv --rules contract.odcs.yaml --format-out json

A contract with several schema objects needs the name of one after #: --rules contract.odcs.yaml#orders.

apiVersion: v3.2.0
kind: DataContract
id: orders-contract
version: 1.0.0
schema:
- name: orders
properties:
- name: order_id
logicalType: integer
primaryKey: true
- name: email
logicalType: string
logicalTypeOptions: {format: email}
quality:
- metric: nullValues
mustBeLessThan: 5
unit: percent
severity: warning
- name: status
enum: [{value: open}, {value: shipped}]
quality:
- metric: rowCount
mustBeGreaterThan: 0

How the parts of a contract are checked:

ContractChecked as
required, unique, primaryKey (one property)Rules, record by record
logicalType: integer, numberThe integer and number rule types
logicalType: boolean, date, timestampThe boolean, date and datetime formats
enumAllowed values (numbers also as their text, as CSV holds them)
logicalTypeOptions: minLength, maxLength, pattern, minimum, maximum, format (email, uuid, url)Rules; a pattern matches anywhere in the value, as in ODCS
Quality metrics nullValues, missingValues, invalidValues, duplicateValues, rowCountContract checks: counted over the file and compared with mustBe, mustBeLessThan, mustBeBetween, ... in rows or percent
primaryKey on several properties, exclusiveMinimum, exclusiveMaximum, multipleOfContract checks
sql, custom and text checks, other types and optionsListed as not checked

Rules report violations per record, as from a rule file, on both engines. Contract checks are listed in their own table, and in the contract key of the JSON report. A failed check of severity error (the default) makes the command exit with 1, and one of severity warning does so with --fail-on-warnings. nullValues counts missing fields, nulls and empty values, because CSV has no other null. SQL checks are never run: a contract from elsewhere could run any SQL. undatum quality --rules and Dataset.validate() check the rules of a contract, not its contract checks.

Legacy Mode (Backward Compatible)​

Simple single-rule validation for quick checks:

# Validate email addresses
undatum validate --rule common.email --fields email data.jsonl

# Validate Russian INN
undatum validate --rule ru.org.inn --fields VendorINN data.jsonl --mode stats

# Output invalid records
undatum validate --rule ru.org.inn --fields VendorINN data.jsonl --mode invalid

Available built-in validation rules:

  • common.email - Email address validation
  • common.url - URL validation
  • ru.org.inn - Russian organization INN identifier
  • ru.org.ogrn - Russian organization OGRN identifier
  • integer - Integer validation

Validation Best Practices​

  1. Use errors for critical issues: Fields that must be correct for data processing
  2. Use warnings for data quality: Issues that should be reviewed but don't block processing
  3. Organize rules by domain: Group related rules in separate files (e.g., user-validation.yml, order-validation.yml)
  4. Version control rule files: Track rule changes and share across teams
  5. Use cross-field rules sparingly: They're more complex and slower to evaluate
  6. Test rules incrementally: Start with basic rules, add complexity as needed

Reference​

Reads: any readable format · Writes: validation report or the (in)valid rows · Memory: streaming · Engines: auto, duckdb, python

undatum validate [OPTIONS] [INPUT_FILE]
ArgumentDescription
INPUT_FILEPath to input file (not needed with --list-rules).
OptionDescriptionDefault
-o, --output TEXTOptional output file path. If not specified, prints to stdout.
-f, --fields TEXTComma-separated list of field names to validate (legacy mode).
-d, --delimiter TEXTCSV delimiter character (auto-detected when omitted).
--quotechar TEXTCSV quote character (iterabledata default '"' when omitted).
--encoding TEXTInput encoding (e.g., 'utf8', 'cp1251'); detected when omitted.
--verbose / --no-verboseEnable verbose logging output.--no-verbose
-F, --format-in TEXTOverride input file format detection (e.g., 'csv', 'jsonl').
--zipfile / --no-zipfileTreat input file as a ZIP archive.--no-zipfile
--rule TEXTValidation rule name (legacy mode, e.g., 'common.email', 'common.url').
--filter, --filter-expr TEXTFilter expression to apply before validation.
--mode TEXTLegacy --rule output: 'invalid' (default), 'valid', 'all', or 'stats' (JSON counts).invalid
--rules TEXTPath to YAML/JSON rule file for rich validation.
--severity TEXTFilter violations by severity: 'error', 'warning', 'info', or 'all' (default).all
-O, --format-out TEXTOutput format: 'text' (default) or 'json'.text
--violation-report TEXTPath to write detailed violation report (JSON format).
--fail-on-warnings / --no-fail-on-warningsTreat warnings as errors (exit with non-zero code).--no-fail-on-warnings
--max-violations INTEGERMaximum number of violations to display (default: 10 for text, 100 for JSON).
--progress / --no-progressShow progress bar.--no-progress
--threads INTEGERWorker processes for rule-file validation chunk parallelism. Omit for sequential processing.
--table, --sheet TEXTTable or sheet name for multi-table sources (Excel, SQLite, lakehouse).
--start-page INTEGERSheet index (0-based) for Excel files.0
--trustAcknowledge pickle deserialization risk when reading pickle sources.
--on-error TEXTParse-error policy: raise (default), skip, or warn.
--error-log TEXTAppend parse errors as JSONL (use with --on-error skip or warn).
--flatten-nestedUnfold nested dict / array-of-dict fields into dotted paths (e.g. city.lat).
--max-nested-depth INTEGERWith --flatten-nested, maximum nest depth to unfold (engine default 5).
--keep-nested-parents / --no-keep-nested-parentsWith --flatten-nested, keep parent dict/array fields alongside dotted children.--keep-nested-parents
--jsonPrint the result as one JSON document (same as --format-out json).
--list-rulesList the built-in rules (format: ...) and exit.
-e, --engine [auto|duckdb|python]Processing engine: auto (default), duckdb, or python.

Deprecated spellings (removed in 3.0): --output-format → --format-out.

See also shared options.