Valibot v1.6: Faster TypeScript checks and more reliable validation

GitHub profile picture of flySewa

Valibot v1.6 is here, with improvements to TypeScript performance, runtime validation, and a few things that make working with schemas easier.

The biggest change is how TypeScript handles Valibot's types. We reworked several core types to reduce the work TypeScript does when checking your code, especially in projects with large object schemas.

On top of that, we made object validation faster, introduced two new actions for checking whitespace, and tightened several format validators that were letting invalid values through.

A big thank you to @yslpn, @kibertoad, @otnc, @Pajimo, @maxazure, @feritcemkahraman, @MaxFreedomPollard, @NgoQuocViet2001, @zanmlakar, @ragib-mrb, @hoanle0126, @lazerg, @xiehuanyi, @ysknsid25, @0xW41th, @hyunbinseo, @meickmeyer, @sillvva, and @mvanhorn for their code contributions, reviews, and helpful discussions.

What's new

  • Faster TypeScript checks: TypeScript now spends less time checking Valibot schemas, particularly in projects with large object schemas.
  • Faster runtime validation: Object schemas and the isbn, creditCard, and imei actions now validate faster.
  • New whitespace actions: The trimmed and nonTrimmed actions let you check for whitespace at the beginning or end of a string.
  • Stricter format validation: The uuid, isbn, base64, ip, and ipv6 actions now reject some values that previously passed validation.
  • Additional fixes: Several improvements address issues with caching, asynchronous schemas, string transformations, and error handling.

Faster TypeScript checks

If you've worked with Valibot in a project with many large object schemas, you may have noticed that TypeScript takes longer to check your code, which affects how quickly your editor responds and how long type checking takes.

This happens because every Valibot schema carries type information, and TypeScript has to compare those types repeatedly as it checks your code. In v1.6, we reworked several of Valibot's types to reduce those comparisons, and you don't need to change your existing schemas to benefit from them.

Variance annotations on core types

When TypeScript compares two schemas with different types, it needs to understand how each schema uses its type internally. Does the type only come out of the schema, for example as a property value or a return type, only go into it as a function parameter, or both?

If that information isn't available, TypeScript works it out for itself by creating test versions of the type and comparing them, which adds to the time it spends checking your code.

TypeScript 4.7 introduced the in and out keywords so library authors can state how their types are used.

In v1.6, we added these keywords to all of Valibot's core interfaces, including schemas, validations, transformations, issues, and Standard Schema. As a result, TypeScript gets this information up front instead of working it out through extra comparisons.

// `out` tells TypeScript that T only comes out of the type,
// for example as a property value or a return type.
interface Producer<out T> {
  readonly value: T;
  readonly get: () => T;
}

// `in` tells TypeScript that T only goes into the type,
// as a function parameter.
interface Consumer<in T> {
  readonly accept: (value: T) => void;
}

Valibot already requires TypeScript 5 or later, so these keywords work for everyone using Valibot with TypeScript.

Simpler object schema types

We also simplified several types that used to compare your schema against Valibot's full schema definitions. For example, the types behind pick and omit checked your schema against the complete definitions of object, looseObject, strictObject, and objectWithRest schemas, which is expensive for TypeScript.

In v1.6, these types only look at the few properties they need, such as the schema's type and entries, so TypeScript has much less to compare.

We applied similar changes to the types for object entries, optional keys, readonly values, and variant schemas, and object schemas without optional keys now skip an internal step they no longer need. None of this changes the types you get from InferInput and InferOutput for commonly used schemas.

Faster runtime validation

The TypeScript improvements help while you're writing and checking code, and we also made a few changes that speed up validation while your application runs.

Faster object validation

When Valibot validates an object, it checks each key in your schema to see whether that key exists in the input. Previously, it ran this check twice for every key, first to decide whether to validate the value and then again to decide whether to use the input value or a default.

In v1.6, we run the check once and reuse the result.

Removing that extra check for every key can make a difference in applications that validate objects frequently, such as incoming requests, form submissions, and API responses.

Faster check digit validation

ISBNs, credit card numbers, and IMEI numbers end with a check digit, which is calculated from the other digits so that certain mistakes in the number can be caught.

Previously, the isbn, creditCard, and imei actions split the input string into an array and parsed each digit before running that calculation. They now read the digits directly from the string, so they no longer create an intermediate array every time validation runs.

Whitespace validation

Valibot v1.6 adds two actions for checking whitespace at the start or end of a string, trimmed and nonTrimmed.

Check for unwanted whitespace with trimmed

The trimmed action checks that a string has no whitespace at the beginning or end, and validation fails if it does.

import * as v from 'valibot';

const ApiKeySchema = v.pipe(v.string(), v.trimmed());

v.parse(ApiKeySchema, 'sk_live_123'); // ok
v.parse(ApiKeySchema, ' sk_live_123'); // throws
v.parse(ApiKeySchema, 'sk_live_123\n'); // throws

The action follows the same character rules as JavaScript's trim() method, so it also catches tabs, line breaks, and non-breaking spaces.

You might wonder why you'd need trimmed when Valibot already has a trim action. The difference is what happens to the original value.

The trim action removes whitespace from the beginning and end of a string, which works well for values such as usernames, where removing accidental spaces is usually fine.

Passwords and API keys are different, because removing whitespace changes the value someone entered. If that value is supposed to match a stored password or key, modifying it could cause unexpected problems.

With trimmed, Valibot rejects the value instead of changing it, so you can ask the user to correct the input.

import * as v from 'valibot';

const UsernameSchema = v.pipe(v.string(), v.trim());
const PasswordSchema = v.pipe(v.string(), v.trimmed());

v.parse(UsernameSchema, ' ada '); // 'ada'
v.parse(PasswordSchema, ' secret '); // throws

Check for whitespace with nonTrimmed

The nonTrimmed action checks the opposite condition and rejects strings that have no whitespace at either end. You can use it when a string is required to start or end with whitespace.

Stricter format validation

We also reviewed several format validators and found cases where they accepted values that didn't meet the expected format. These fixes make validation more accurate, but they also change behavior, so some values that passed in v1.5.0 may now fail validation.

UUID

A UUID contains two digits that define its version and variant. The version identifies the UUID format, and the variant identifies the layout it follows.

Previously, the uuid action checked the overall string format without validating these two digits, so a UUID with an invalid version or variant could still pass. In v1.6, the action checks both against RFC 9562, the specification that defines UUIDs.

import * as v from 'valibot';

const IdSchema = v.pipe(v.string(), v.uuid());

v.parse(IdSchema, '550e8400-e29b-41d4-a716-446655440000'); // ok

// Invalid version
v.parse(IdSchema, '550e8400-e29b-01d4-a716-446655440000'); // throws

// Invalid variant
v.parse(IdSchema, '550e8400-e29b-41d4-c716-446655440000'); // throws

The Nil UUID (all zeros) and the Max UUID (all f) are still accepted, because RFC 9562 explicitly allows them.

ISBN

Every 13-digit ISBN starts with either 978 or 979, since these are the prefixes assigned to books.

Previously, the isbn action checked the number of digits and the check digit without verifying the prefix. It now checks the prefix as well, so a 13-digit number with an invalid prefix no longer passes, even if its check digit is correct.

Base64, IP, and IPv6

In v1.5, we fixed an issue in the email action where certain unusual Unicode characters could pass validation unexpectedly.

One example is the Kelvin sign (K, U+212A), which looks like a regular capital K but is a different Unicode character. Because of that, a case-insensitive regular expression could treat it as a K and let it through.

We found the same issue in the base64 action and in the zone ID validation used by ip and ipv6, and these validators now reject those characters too.

Values that are now accepted

A few fixes in this release go the other way and accept valid values that were being rejected before.

  • hexadecimal now accepts the uppercase prefixes 0X and 0H, such as 0X1F, and octal now accepts the uppercase prefix 0O, such as 0O17.
  • creditCard now accepts Discover cards with prefixes from 644 to 649.

Other fixes

Alongside the performance improvements and validation changes, v1.6 includes several smaller fixes across Valibot.

Runtime and caching

base64 and jwsCompact could throw a RangeError when processing very long strings in V8, the JavaScript engine used by Chrome and Node.js. Both actions now handle these strings correctly.

cache and cacheAsync build keys from the input and configuration to retrieve cached results.

Previously, a string input could produce the same key as a configuration value, which caused Valibot to return a result cached for something else. We now escape strings to prevent these collisions.

Schema types and validation

pick and omit returned never when used with an objectWithRestAsync schema that had an asynchronous rest schema. They now return the expected schema type.

checkItems and checkItemsAsync kept collecting issues after finding an invalid item, even when abortEarly was enabled. They now stop at the first invalid item.

String and path handling

toCamelCase, toKebabCase, toPascalCase, and toSnakeCase now identify word boundaries correctly for rare letters that JavaScript represents using two characters, including letters from historic and mathematical alphabets.

getDotPath and flatten used to drop object keys that were empty strings, which could cause validation errors to point to the wrong field. Both now preserve those keys.

Deprecations

We deprecated the unused OptionalEntrySchema and OptionalEntrySchemaAsync types.

Upgrade to v1.6

You can upgrade to Valibot v1.6 without changing your existing schema definitions.

npm install valibot@1.6.0

The change most likely to need your attention is the stricter uuid action. IDs that only look like a UUID, such as 11111111-1111-1111-1111-111111111111 in tests or seed data, no longer pass.

If you need to accept such IDs, use regex with your own pattern instead. The other stricter checks only reject values that rarely appear in real data.

Try Valibot v1.6

If there's a validator, transformation, or guide you'd like to see next, let us know on Discord or open a discussion on GitHub.

New to Valibot? Start with our quick start guide. Coming from Zod? Take a look at our migration guide.

Edit page

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of @evilmartians
  • GitHub profile picture of @vasilii-kovalev
  • GitHub profile picture of @ruiaraujo012
  • GitHub profile picture of @hyunbinseo
  • GitHub profile picture of @nickytonline
  • GitHub profile picture of @kibertoad
  • GitHub profile picture of @caegdeveloper
  • GitHub profile picture of @Thanaen
  • GitHub profile picture of @ysknsid25
  • GitHub profile picture of @dslatkin