---
title: Validators
section: Core Concepts
description: Validate your data and provide instant feedback to your users by using validators.
---

While [transformers](/docs/transformers) can help auto-heal your data and bring consistency, they don't cover all cases. What if the email provided is invalid or the last name is blank? Validators have been designed to address this problem and provide feedback to your end-users, so they can fix these errors.

Let's see how we can extend our previous example to make sure that both email and last name are required. We will be using pipe syntax, like in transformers.

```json
[
  {
    "label": "First name",
    "transformers": "trim|capitalize"
  },
  {
    "label": "Last name",
    "transformers": "trim|capitalize",
    "validators": "required" // [tl! highlight]
  },
  {
    "label": "Phone",
    "transformers": "trim"
  },
  {
    "label": "Email",
    "transformers": "trim|lowercase",
    "validators": "required" // [tl! highlight]
  },

]
```

## Chaining validators

Validators can be chained using the pipe syntax. Let's say we want to make sure that the email provided is valid. We can use the `email` validator.

```json
[
  {
    "label": "First name",
    "transformers": "trim|capitalize"
  },
  {
    "label": "Last name",
    "transformers": "trim|capitalize",
    "validators": "required"
  },
  {
    "label": "Phone",
    "transformers": "trim"
  },
  {
    "label": "Email",
    "transformers": "trim|lowercase",
    "validators": "required|email" // [tl! highlight]
  },

]
```

## Available validators

| Validator | Description |
|-----------|-------------|
| `between:*min*,*max*` | Asserts that the field under validation has a numeric value between min and max (inclusive). |
| `boolean` | Asserts that the field under validation is able to be cast as a boolean. Accepted inputs are true, false, 1, 0, yes, no, y, and n. |
| `date:*format*,...` | Asserts that the field under validation can be matched to one of the given formats. The validation rule supports all formats supported by date-fns [parse](https://date-fns.org/docs/parse) function. When no format is specified, the validation rule asserts that the field under validation can be matched to ISO 8601 format. |
| `email` | Asserts that the field under validation is formatted as an e-mail address. |
| `in:*provider*` | Asserts that the field under validation is provided by the specified [data provider](/docs/data-providers). |
| `integer` | Asserts that the field under validation is an integer. |
| `length:*min*,*max*` | Asserts that the field under validation has a length between the given min and max (inclusive). |
| `number` | Asserts that the field under validation is a number. |
| `required` | Asserts that the field under validation is present in the input data and is not empty. |
| `unique` | Asserts that the field under validation is unique across all the rows in the input data. Empty strings are ignored. *(This is a context validator - see [Validators with Context](#validators-with-context) below)* |

## Custom Validators

On top of the built-in validators, you can always build your own validators so that you can report data errors and issues according to your requirements. To do this you will need to name your validator and associate it with a callback to be called every time it is used. You can add as many validators as necessary.

```js
{
  "validators": {
    "my-validator": function(record, field) {
      ...
    },
    "my-validator-with-single-arg": function(record, field, arg1) {
      ...
    },
    "my-validator-with-multiple-args": function(record, field, arg1, arg2, arg3) {
      ...
    }
  }
}
```

Let's see how we can add a validator called `phone` to validate phone numbers using the `google-libphonenumber` library. In case something is wrong, we need to return the error message. Otherwise, we can return `true` to indicate that the provided value passes the validation. Please note that you can not overwrite a validator that already exists and you will get an error if you try to do that.

```js

      try {
        const parsed = PhoneNumberUtil.getInstance().parseAndKeepRawInput(value);
        if (!PhoneNumberUtil.getInstance().isValidNumber(parsed)) {
          return 'Must be a valid phone number.';
        }
      } catch (e) {
        return 'Must be a valid phone number.';
      }

      return true;
    }
  }
};
```

That's all! You can use the pipe syntax to use the new validator.

```json
{
  "fields": [
    {
      "label": "First name",
      "transformers": "trim"
    },
    {
      "label": "Last name",
      "transformers": "trim"
    },
    {
      "label": "Phone",
      "transformers": "trim",
      "validators": "phone"
    },

  ]
}
```

## Passing additional arguments

Validators can be made more dynamic by accepting additional arguments. Let's enhance our example to accept a country code as the first argument.

```js

      try {
        const parsed = defaultCountry
          ? PhoneNumberUtil.getInstance().parseAndKeepRawInput(value, defaultCountry)
          : PhoneNumberUtil.getInstance().parseAndKeepRawInput(value);
        if (!PhoneNumberUtil.getInstance().isValidNumber(parsed)) {
          return 'Must be a valid phone number.';
        }
      } catch (e) {
        return 'Must be a valid phone number.';
      }

      return true;
    }
  }
};
```

## Validators with Context

By default, validators validate one record at a time. However, there are scenarios where you need to validate a field across **all records** in the dataset. For example, checking if a value is unique across all rows or validating relationships between records.

Context validators receive all records as an array instead of a single record, allowing cross-record validation. It is required to add errors directly to individual records using `record.addError`. Please note that the built-in `unique` validator is implemented as a context validator since it needs to compare values across all records.

### Defining Custom Context Validators

Context validators must be defined in a separate `withContext` object in your configuration. Here is how you can define a custom context validator called `valid-manager` that checks if the "Manager ID" field references a valid employee in the dataset:

```js
{
  "validators": {
    // Regular validators go here
    "phone": (record, key) => {
      // ... regular validator logic
      return true; // or error message
    },
    "withContext": {
      "valid-manager": (context, key) => {
      const bag = 'valid-manager'; // Error namespace

      // First pass: collect all employee IDs and clear previous errors
      const employeeIds = new Set();
      for (const record of context) {
        record.clearErrors(bag);
        const empId = record.get('Employee ID');
        if (empId) {
          employeeIds.add(empId);
        }
      }

      // Second pass: validate manager IDs
      for (const record of context) {
        const managerId = record.get(key);

        if (managerId === '') {
          continue; // Skip if no manager
        }

        if (!employeeIds.has(managerId)) {
          record.addError(key, 'Manager ID must reference a valid employee.', bag);
        }
      }
    }
  }
}
```

**Understanding error bags:** The third parameter in `addError()` is called a "bag" - it's an error namespace that allows you to group and clear errors by validator. This is crucial for context validators because when data changes and validation re-runs, you need to clear only the errors from that specific validator without affecting errors from other validators. Always use `record.clearErrors(bag)` at the start of your context validator to prevent stale errors.

You can then use the context validator just like any other validator:

```json

  ]
}
```

Please note that context validators are more powerful but also more complex than regular validators. They require careful handling of errors and efficient algorithms to avoid performance issues, especially with large datasets.

### Important Notes

- Context validators have access to the entire dataset, so they run once for all records rather than once per record
- Context validators can access **any field** from any record, not just the field being validated
- Always use `record.addError(key, message, bag)` with a bag parameter to namespace your errors
- Always call `record.clearErrors(bag)` before adding new errors to avoid stale validation results
- Use `Map` or `Set` to track seen values and their associated records for better performance: O(n) vs O(n²) with nested loops

## Data Providers

Validators are great when you want to validate data synchronously. However, there are cases where you want to fetch data asynchronously from your API. For that you will need to use [data providers](/docs/data-providers).

In the next step we are going to extend the above example to push the normalized data to our API using webhooks.

[Have a look at webhooks &rarr;](/docs/webhooks)
