# CSV Validator: Check Rows and Columns by Rules (`ucchiii/csv-validator`) Actor

Check CSV, TSV or Apify dataset rows against your rules: types, required, unique, min/max, length, regex, allowed values, dates, column order, row count, duplicates. Lists each bad row and column with the reason. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/csv-validator.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.01 / 1,000 validated rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**Check a CSV, TSV or Apify dataset against your own rules and get every bad row and column listed with the reason**

**For anyone who has to trust a table before it goes somewhere: a data team checking a file before an import, an agency checking a CSV a client delivered, or someone checking a migration export before the old system is switched off.** Give this Actor file URLs (or Apify datasets), describe what a good row looks like in a small JSON document, and get **one output row per problem (source, row, column, rule, value, reason)** plus a **REPORT** with a pass/fail result and counts by rule and by column.

**$0.0015 per checked file plus $0.00002 per checked row ($0.02 per 1,000 rows), header row not counted.** Examples: a 10-row file costs $0.0017, a 100-row file $0.0035, a 1,000-row file $0.0215. **The $5 monthly free credit covers about 230 files of 1,000 rows.** The rows that list the problems are free. Failed, empty and binary files and the demo are free. No scraping, no API keys.

**Try it free: clear the prefilled URL and the datasets and press Start.** The demo checks a built-in sample CSV against built-in sample rules, is not charged and every output row carries `_demo: true`.

### The problems it solves

- **"Will this file load?"** Check column names and order, required values, whole numbers, dates and e-mail addresses before an import fails halfway.
- **A delivered CSV has to match the agreement.** Write the agreement once as rules (exact columns, allowed values, number ranges, no duplicate rows) and check each delivery in seconds. The list of problems goes back to the sender as it is.
- **Before a data migration.** Find empty required cells, text in number columns, IDs that appear twice and values that do not match a format, with the row number of each.
- **Output of an earlier Apify step.** Check a dataset the same way, from a scheduled run or through the API.

### What it checks

Per column (`columns`):

| Rule | Meaning |
|---|---|
| `type` | `string` (default), `integer`, `number`, `boolean` (true/false, yes/no, 1/0, y/n), `date`, `email` (format check only, not whether the address exists), `url` (http or https) |
| `required` | the cell must not be empty |
| `unique` | no other row may hold the same value (empty cells are ignored) |
| `min`, `max` | number range, for `integer` and `number` columns |
| `minLength`, `maxLength` | number of characters |
| `pattern` | a regular expression that must be found in the cell (use `^` and `$` to match the whole cell) |
| `enum` | list of allowed values |
| `format` | for `date`: the date pattern, default `%Y-%m-%d` (for example `%d/%m/%Y`) |

Cells are trimmed before they are checked. An empty cell is only reported by `required`; the other rules skip it.

For the whole file:

| Key | Meaning |
|---|---|
| `expectedColumns` | the column names in the order you expect |
| `allowExtraColumns` | `true` to allow columns that are not in `expectedColumns` (default `false`) |
| `rowCountMin`, `rowCountMax` | allowed number of data rows |
| `duplicateRows` | `true` to report a row whose values in every column equal an earlier row |

Rows that have more or fewer cells than the header are always reported (`column_count`).

### Rules example

```json
{
  "expectedColumns": ["order_id", "email", "quantity", "ordered_on", "status", "coupon"],
  "rowCountMin": 1,
  "duplicateRows": true,
  "columns": {
    "order_id":   { "type": "integer", "required": true, "unique": true, "min": 1 },
    "email":      { "type": "email", "required": true },
    "quantity":   { "type": "integer", "min": 1, "max": 99 },
    "ordered_on": { "type": "date", "format": "%Y-%m-%d" },
    "status":     { "enum": ["new", "paid", "shipped"] },
    "coupon":     { "pattern": "^[A-Z]{4}-\\d{4}$", "maxLength": 9 }
  }
}
```

Input:

```json
{
  "fileUrls": ["https://example.com/exports/orders.csv"],
  "rules": { "...": "as above" },
  "maxErrors": 1000
}
```

A dataset works the same way with `"datasetIds": ["<dataset id>"]`; each item is a row and its keys are the column names.

### Output

- **Dataset**: one row per problem.
  ```json
  { "source": "https://example.com/exports/orders.csv", "row": 17, "column": "quantity", "rule": "max", "value": "120", "message": "120 is above the maximum 99." }
  ```
  `row` is the row as a spreadsheet shows it: the header is row 1 and the first data row is row 2 (a quoted cell with line breaks is one row). For a dataset it is the item number. Problems about the whole file (a missing column, too few rows) have an empty `row`. `value` is cut to 200 characters. A file that could not be read produces one row with the rule `file_unreadable` and the reason.
- **REPORT** (key-value store):
  ```json
  { "valid": false, "totalRows": 4200, "errorCount": 31, "truncated": false,
    "byRule": { "type": 12, "required": 10, "max": 9 }, "byColumn": { "quantity": 15, "email": 12, "status": 4 },
    "encoding": "shift_jis", "delimiter": "comma",
    "files": [ { "source": "...", "status": "ok", "rows": 4200, "errorCount": 31, "valid": false, "encoding": "shift_jis", "delimiter": "comma" } ] }
  ```
  `valid` is true only when every file was checked and no problem was found. With several files, `encoding` and `delimiter` show `mixed` when they differ; each file's own values are in `files`.

### Input options

- **Encoding** and **delimiter** are detected for you (byte-order mark, valid UTF-8, then a statistical detector for Shift_JIS, Windows-1252, Windows-1251 and others; comma, semicolon, tab or pipe from the first lines). The REPORT shows what was read; set them yourself if the guess is wrong.
- **First row is a header**: turn off for files without one. Columns are then called `column1`, `column2`, ... (or take the names from `expectedColumns`).
- **Maximum problems** (`maxErrors`, default 1,000, at most 10,000): checking stops once this many problems are found in the run and the REPORT says `truncated: true`. Rows checked up to that point are charged; files after that point are not checked. File-wide row count rules are not judged on a truncated check.

### FAQ

**Does it change my file?** No. It only reads it.

**What counts as a row for the price?** Each data row that was checked. The header row, blank lines and the problem rows in the output do not count. A file with no data rows, an empty file or a binary file costs nothing.

**What happens when the maximum cost of the run is too low?** Before checking a file, the Actor makes sure the budget covers the file fee and all its rows. If it does not, that whole file is skipped and the REPORT lists it as `skipped`. If no file fits, nothing is checked or charged and the run ends as Failed.

**Is the regular expression safe to run on my data?** Each pattern check has a time limit of 10 ms per cell and only cells up to 2,000 characters are matched; a longer cell is reported as failing. If a pattern is too slow on a value (for example nested repeats like `(a+)+`), that cell is reported as "could not be checked", and after three such cells pattern checks for that column stop. Simplify the pattern if you see this.

**Dates?** `date` uses Python-style patterns (`%Y`, `%m`, `%d`, `%H`, `%M`, `%S`, `%b`, `%y`, ...). A real calendar date is required (`2025-02-30` fails).

**Excel files?** Not supported: save the sheet as CSV first. Excel workbooks, PDFs and other binary files are rejected for free.

**Can I check several files in one run?** Yes, up to 50 files or datasets. `unique` and `duplicateRows` work within one file.

### Limits (cannot be raised by input)

- 50 MB per file; 50 files or datasets per run; 2,000,000 data rows per file or dataset
- A download is tried up to 3 times when the server is slow or answers with a temporary error (HTTP 429, 5xx); a clear error such as 404 is not retried. The timeout is 60 seconds per request
- Source URLs must be public `http` or `https` links. Addresses on internal networks (localhost, private ranges, cloud metadata) are blocked, also after redirects
- Text files only (CSV, TSV, semicolon or pipe separated)
- Up to 10,000 problems per run

### More tools from the same developer

- [Dataset Column Profiler](https://apify.com/ucchiii/dataset-column-profiler) — profile every column of a dataset or CSV: types, missing values, distinct counts, top values and statistics
- [CSV Encoding Converter](https://apify.com/ucchiii/csv-encoding-converter) — detect the encoding of CSV and text files and convert them to UTF-8 (or another encoding)
- [TSV to CSV Converter](https://apify.com/ucchiii/tsv-csv-converter) — convert between TSV, CSV, semicolon and pipe-delimited files, keeping quoted cells and line breaks intact
- [Dataset Type Caster](https://apify.com/ucchiii/dataset-type-caster) — turn text columns into real numbers, booleans and dates: currencies, 1,200 vs 1.200, and Japanese era dates
- [CSV to JSON Converter](https://apify.com/ucchiii/csv-to-json) — turn CSV files into typed JSON: encoding and delimiter detected, numbers and booleans typed, dotted headers nested, array, NDJSON or keyed output

# Actor input Schema

## `fileUrls` (type: `array`):

Public http(s) links to CSV or TSV files, one per entry (up to 50 files and 50 MB each). Links to internal networks are blocked. Leave this AND 'Apify datasets' empty to run a free demo on a built-in sample (not charged).

## `datasetIds` (type: `array`):

Optional. Dataset IDs whose items are the rows to check (each item is an object; the keys are the column names). Each dataset is checked as one table and counts as one file.

## `rules` (type: `object`):

Your rules as JSON. 'columns' maps a column name to its rules: type (string, integer, number, boolean, date, email, url), required, unique, min, max (numbers), minLength, maxLength, pattern (regular expression, searched in the cell), enum (allowed values), format (date pattern, default %Y-%m-%d). File-wide keys: expectedColumns (names in order), allowExtraColumns, rowCountMin, rowCountMax, duplicateRows. Empty = only rows with a wrong number of cells are reported. See the README for examples.

## `encoding` (type: `string`):

Text encoding of the CSV files. 'auto' checks the byte-order mark, then whether the file is valid UTF-8, then a statistical detector (Shift_JIS, Windows-1252, Windows-1251 and more); the REPORT shows what was read. Choose one yourself if the guess is wrong. Default: auto.

## `delimiter` (type: `string`):

Column separator of the files. 'auto' looks at the first lines (the REPORT shows what was used). Not used for datasets. Default: auto.

## `hasHeader` (type: `boolean`):

Turn off for files without a header row: columns are then named column1, column2 and so on (or by 'expectedColumns' when given), and every row is checked and charged. Not used for datasets. Default: on.

## `maxErrors` (type: `integer`):

Checking stops once this many problems are found in the run (1 to 10,000) and the REPORT says truncated: true. Rows checked up to that point are charged. Default: 1000.

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ],
  "rules": {
    "expectedColumns": [
      "sepal_length",
      "sepal_width",
      "petal_length",
      "petal_width",
      "species"
    ],
    "rowCountMin": 1,
    "columns": {
      "sepal_length": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "sepal_width": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "petal_length": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "petal_width": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 2
      },
      "species": {
        "required": true,
        "enum": [
          "setosa",
          "versicolor",
          "virginica"
        ]
      }
    }
  },
  "encoding": "auto",
  "delimiter": "auto",
  "hasHeader": true,
  "maxErrors": 1000
}
```

# Actor output Schema

## `problems` (type: `string`):

One row per problem: source, row, column, rule, value and reason. Empty when the data passes every rule. Download as CSV, JSON, Excel and more.

## `report` (type: `string`):

Record REPORT: valid true or false, total rows, number of problems, counts by rule and by column, the encoding and delimiter that were read, and one entry per file.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "fileUrls": [
        "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
    ],
    "rules": {
        "expectedColumns": [
            "sepal_length",
            "sepal_width",
            "petal_length",
            "petal_width",
            "species"
        ],
        "rowCountMin": 1,
        "columns": {
            "sepal_length": {
                "type": "number",
                "required": true,
                "min": 0,
                "max": 10
            },
            "sepal_width": {
                "type": "number",
                "required": true,
                "min": 0,
                "max": 10
            },
            "petal_length": {
                "type": "number",
                "required": true,
                "min": 0,
                "max": 10
            },
            "petal_width": {
                "type": "number",
                "required": true,
                "min": 0,
                "max": 2
            },
            "species": {
                "required": true,
                "enum": [
                    "setosa",
                    "versicolor",
                    "virginica"
                ]
            }
        }
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/csv-validator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"],
    "rules": {
        "expectedColumns": [
            "sepal_length",
            "sepal_width",
            "petal_length",
            "petal_width",
            "species",
        ],
        "rowCountMin": 1,
        "columns": {
            "sepal_length": {
                "type": "number",
                "required": True,
                "min": 0,
                "max": 10,
            },
            "sepal_width": {
                "type": "number",
                "required": True,
                "min": 0,
                "max": 10,
            },
            "petal_length": {
                "type": "number",
                "required": True,
                "min": 0,
                "max": 10,
            },
            "petal_width": {
                "type": "number",
                "required": True,
                "min": 0,
                "max": 2,
            },
            "species": {
                "required": True,
                "enum": [
                    "setosa",
                    "versicolor",
                    "virginica",
                ],
            },
        },
    },
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/csv-validator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ],
  "rules": {
    "expectedColumns": [
      "sepal_length",
      "sepal_width",
      "petal_length",
      "petal_width",
      "species"
    ],
    "rowCountMin": 1,
    "columns": {
      "sepal_length": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "sepal_width": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "petal_length": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 10
      },
      "petal_width": {
        "type": "number",
        "required": true,
        "min": 0,
        "max": 2
      },
      "species": {
        "required": true,
        "enum": [
          "setosa",
          "versicolor",
          "virginica"
        ]
      }
    }
  }
}' |
apify call ucchiii/csv-validator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,ucchiii/csv-validator"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/FiMeVY0DV1OocDC1h/builds/5l2wS4jgI3tAJ9n4k/openapi.json
