---
title: length
description: Creates a length validation action.
source: /actions/length/length.ts
contributors:
  - fabian-hiller
  - yslpn
---

import { ApiList, Link, Property } from '~/components';
import { properties } from './properties';

# length

Creates a length validation action.

```ts
const Action = v.length<TInput, TRequirement, TMessage>(requirement, message);
```

## Generics

- `TInput` <Property {...properties.TInput} />
- `TRequirement` <Property {...properties.TRequirement} />
- `TMessage` <Property {...properties.TMessage} />

## Parameters

- `requirement` <Property {...properties.requirement} />
- `message` <Property {...properties.message} />

### Explanation

With `length` you can validate the length of a string or array. For strings, length is measured like JavaScript's `value.length`, i.e. by UTF-16 code units. For arrays, length is measured by the number of items. If the input does not match the `requirement`, you can use `message` to customize the error message.

> If you need to validate the number of user-perceived characters, use <Link href="../graphemes/">`graphemes`</Link> instead.

## Returns

- `Action` <Property {...properties.Action} />

## Examples

The following examples show how `length` can be used.

### String schema

Schema to validate a string with a length of 8 UTF-16 code units.

```ts
const StringSchema = v.pipe(
  v.string(),
  v.length(8, 'The string must be 8 UTF-16 code units long.')
);
```

### Array schema

Schema to validate the length of an array.

```ts
const ArraySchema = v.pipe(
  v.array(v.number()),
  v.length(100, 'The array must contain 100 numbers.')
);
```

## Related

The following APIs can be combined with `length`.

### Schemas

<ApiList
  items={['any', 'array', 'custom', 'instance', 'string', 'tuple', 'unknown']}
/>

### Methods

<ApiList items={['pipe']} />

### Actions

<ApiList items={['graphemes']} />

### Utils

<ApiList items={['isOfKind', 'isOfType']} />
