> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/account-validator.md).

# Account validator

Reject an enrolment with field-level error messages before anything is created, with runtime.scriptable.scriptableAccountValidator.

The account validator lets a tenant script check an enrolment before The Wallet Crew does anything with it. The script receives the submitted account and returns a list of errors, each tied to a form field or to the account as a whole; when the list is not empty, the enrolment is refused with those messages and nothing is created, no email is sent and no flow runs. This page is the reference for `runtime.scriptable.scriptableAccountValidator`.

It is the right tool for business rules that the form's own field validation cannot express: a minimum age, a postal code format per country, a list of excluded email domains, a membership number checked against an external system. It is not meant to change the account: values are completed by the [pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md) in the account API and by the steps of a [registration flow](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/customer-pipeline-element.md).

<details>

<summary><strong>Real-world examples</strong></summary>

* A club refuses enrolments of customers under 18, with the message shown next to the birth date field.
* A retailer operating in two countries checks the postal code format of the chosen country.
* A B2B program only accepts email addresses from the domains of its partner companies.

</details>

## Registration

The key is `runtime.scriptable.scriptableAccountValidator`. Registering it is enough: no configuration file refers to it.

```js
export default function (context) {
  context.register('runtime.scriptable.scriptableAccountValidator', {
    Validate: async (account) => []
  });
}
```

## When it runs

The validator runs at the very start of every enrolment submission, `POST /api/{tenantId}/customer`, whoever the caller is: a customer filling in the form, an admin console user, an API key. A rule that should apply only to customers checks a value that only the public form sends. It runs before the customer is identified, before the identity-confirmation email and before any registration flow, inside the request. The errors it returns are combined with those of any other account validation the tenant runs, and reported together.

## Handlers

| Method     | Parameters | Returns                                              | Required |
| ---------- | ---------- | ---------------------------------------------------- | -------- |
| `Validate` | `account`  | an array of `{ Detail, Field? }`, or a promise of it | Required |

`account` is the account as submitted: a flat dictionary keyed by form field (`account.email`, `account.birthDate`), with identifiers, when the caller sends any, under `id.<key>`. Values are as the form sent them, usually strings. The conventions for reading keys are described in [Data objects](https://docs.thewalletcrew.io/developers-guides/scripting/data-objects.md).

## Return value

The handler always returns an array, empty when the account is valid. Each error uses PascalCase keys:

| Key      | Type   | Meaning                                                                                      |
| -------- | ------ | -------------------------------------------------------------------------------------------- |
| `Detail` | string | Required. The message, as shown to the person who submitted the form.                        |
| `Field`  | string | The form field the message belongs to. Omitted, the message is about the account as a whole. |

When the array is not empty, the request answers `400` with a validation problem whose `errors` are grouped by field; messages without a field are grouped under the empty key `""`. Messages are returned as written, so a tenant with several languages writes them in the language of the form or returns a message per language the front end can pick from.

## Errors and edge cases

* **Validate throws or its promise rejects**: the enrolment request fails with an error, not with a validation problem. A validator that depends on an external system decides explicitly what an outage means (accept, or refuse with a clear message) instead of throwing.
* **Validate returns nothing**: always return an array; `[]` is the valid answer.
* **Validate is missing** from the registered object: the request fails when the validator runs.
* **No script registers the key**: no validation runs and the enrolment goes on.
* **Several files register the key**: the last registered wins, and the load order of files is not defined.

## Example

The validator enforces a minimum age from a `birthDate` field sent as `YYYY-MM-DD`, and a postal code format per country. The date is read field by field rather than with `new Date(y, m, d)`, which counts months from zero and uses the server's time zone.

```js
const MINIMUM_AGE = 18;
const POSTAL_CODE_FORMATS = {
  FR: /^\d{5}$/,
  BE: /^\d{4}$/,
  GB: /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i
};

function ageOn(birthDate, today) {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(birthDate ?? '');
  if (!match) {
    return null;
  }
  const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
  let age = today.getUTCFullYear() - year;
  const beforeBirthday = today.getUTCMonth() + 1 < month || (today.getUTCMonth() + 1 === month && today.getUTCDate() < day);
  if (beforeBirthday) {
    age -= 1;
  }
  return age;
}

async function validate(account) {
  const errors = [];

  if (account.birthDate) {
    const age = ageOn(account.birthDate, new Date());
    if (age === null) {
      errors.push({ Field: 'birthDate', Detail: 'The birth date is not valid.' });
    } else if (age < MINIMUM_AGE) {
      errors.push({ Field: 'birthDate', Detail: `Members must be at least ${MINIMUM_AGE} years old.` });
    }
  }

  const format = POSTAL_CODE_FORMATS[account.country];
  if (format && account.postalCode && !format.test(account.postalCode.trim())) {
    errors.push({ Field: 'postalCode', Detail: 'The postal code does not match the selected country.' });
  }

  return errors;
}

export default function (context) {
  context.register('runtime.scriptable.scriptableAccountValidator', {
    Validate: validate
  });
}
```

## Checking the result

Calling `POST /api/{tenantId}/customer` with an account that breaks a rule returns `400` with the messages under `errors`, keyed by field; the same call with a valid account goes on as before.

## Common pitfalls

* `Field` names a key that is not a field of the form, so a front end that displays errors by field has nowhere to show the message.
* The handler is registered as `validate`: handler names are case-sensitive and must be `Validate`.
* A slow external check delays every enrolment, including those of admin console users.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/account-validator.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
