Migrate from Joi
Migrating from Joi to Valibot is straightforward in most cases since both APIs share the same basic concepts. Beyond a much smaller bundle size, one of the biggest benefits of migrating is that Valibot infers the TypeScript type of your data from your schema, which eliminates the need to maintain separate type definitions. The following guide will help you migrate step by step and also point out important differences.
Replace imports
The first thing to do after installing Valibot is to update your imports. Just change your Joi imports to Valibot's and replace all occurrences of Joi. with v..
// Change this
import Joi from 'joi';
const Schema = Joi.object({ key: Joi.string().required() });
// To this
import * as v from 'valibot';
const Schema = v.object({ key: v.string() });Restructure code
One of the biggest differences between Joi and Valibot is the way you further validate a given type. In Joi, you chain methods like .email and .max. In Valibot you use pipelines to do the same thing. This is a function that starts with a schema and is followed by up to 19 validation or transformation actions.
// Change this
const Schema = Joi.string().email().max(30);
// To this
const Schema = v.pipe(v.string(), v.email(), v.maxLength(30));Due to the modular design of Valibot, also all other methods like .validate have to be used a little bit differently. Instead of chaining them, you usually pass the schema as the first argument and move any existing arguments one position to the right. Where Joi returns an object with value and error, safeParse returns a result object with output and issues.
// Change this
const { value, error } = Joi.string().validate('foo');
// To this
const result = v.safeParse(v.string(), 'foo');
if (result.success) {
console.log(result.output);
} else {
console.log(result.issues);
}If you prefer an exception to be thrown on invalid input, as with Joi.attempt or Joi.assert, use parse instead.
// Change this
const value = Joi.attempt('foo', Joi.string());
// To this
const value = v.parse(v.string(), 'foo');We recommend that you read our mental model guide to understand how the individual functions of Valibot's modular API work together.
Infer types
Joi does not infer TypeScript types from your schemas, which usually forces you to maintain separate type definitions. With Valibot, you can remove these duplicate definitions and infer the types directly from your schemas. See the infer types guide for more details.
const UserSchema = v.object({
name: v.string(),
email: v.pipe(v.string(), v.email()),
});
type User = v.InferOutput<typeof UserSchema>;
// { name: string; email: string }Required by default
Joi schemas are optional by default. To reject undefined, you have to append .required() to each schema. Valibot works the other way around. Every schema is required by default, and you explicitly mark schemas as optional by wrapping them with optional, nullable or nullish.
// Change this
const Schema = Joi.object({
name: Joi.string().required(),
email: Joi.string(),
});
// To this
const Schema = v.object({
name: v.string(),
email: v.optional(v.string()),
});There is one detail to watch out for. Joi's string schema rejects empty strings by default. If you rely on this behavior, add the nonEmpty action to your pipeline.
// Change this
const Schema = Joi.string().required();
// To this
const Schema = v.pipe(v.string(), v.nonEmpty());No implicit type conversion
By default, Joi converts values to the expected type before validating them. For example, Joi.number() accepts the string '24' and converts it to the number 24, and Joi.date() converts ISO strings to Date objects. Valibot never changes your data implicitly. If you rely on type conversion, use a pipeline with an explicit transform action or one of the dedicated transformation actions like toNumber or toDate. This forces you to explicitly define the input, resulting in safer code.
// Change this
const NumberSchema = Joi.number();
// To this
const NumberSchema = v.pipe(v.string(), v.toNumber());// Change this
const DateSchema = Joi.date();
// To this
const DateSchema = v.pipe(v.string(), v.toDate());Keep in mind that toNumber behaves like JavaScript's Number function and therefore converts empty strings to 0, and that toDate accepts any string that the Date constructor can parse. For stricter validation, we recommend adding actions like decimal or isoTimestamp to validate the formatting of the string before converting it.
const NumberSchema = v.pipe(v.string(), v.decimal(), v.toNumber());
const DateSchema = v.pipe(v.string(), v.isoTimestamp(), v.toDate());Collect all issues
Another difference is that Joi stops validation after the first error by default. Valibot collects all issues instead. If you prefer Joi's behavior for performance reasons, you can pass a configuration object with abortEarly: true as the third argument to parse or safeParse.
// Change this
const { error } = Schema.validate(input);
// To this
const result = v.safeParse(Schema, input, { abortEarly: true });Change names
Most of the names are similar to Joi. However, there are some exceptions. The following table shows all names that have changed.
| Joi | Valibot |
|---|---|
allow(null) | nullable |
alphanum | regex |
alternatives | union, variant |
append | Object merging |
assert | parse |
attempt | parse |
concat | Object merging |
custom | check, rawCheck, rawTransform |
default | optional |
equal | literal, picklist |
external | checkAsync |
forbidden | optional with never |
greater | gtValue |
guid | uuid |
hex | hexadecimal |
invalid | notValue, notValues |
isoDate | isoDate, isoDateTime, isoTimestamp |
items | Item argument of array |
keys | Object merging |
length | length, size, entries |
less | ltValue |
link | lazy |
lowercase | toLowerCase |
max | maxLength, maxValue, maxEntries |
min | minLength, minValue, minEntries |
multiple | multipleOf |
negative | ltValue |
ordered | tuple, tupleWithRest |
pattern | regex, record, objectWithRest |
positive | gtValue |
try | union, variant |
unique | checkItems |
unknown | looseObject |
uppercase | toUpperCase |
uri | url |
valid | literal, picklist |
validate | parse, safeParse |
validateAsync | parseAsync, safeParseAsync |
Other details
Below are some more details that may be helpful when migrating from Joi to Valibot.
Unknown object keys
By default, Joi rejects unknown keys when validating objects. This matches Valibot's strictObject schema. If you use .unknown() to keep unknown keys, use looseObject instead. If you use the stripUnknown option to remove them, object is the right choice. See the objects guide for more details.
// Change this
const ObjectSchema = Joi.object({ key: Joi.string().required() });
// To this
const ObjectSchema = v.strictObject({ key: v.string() });Cross-field validation
Joi uses Joi.ref to reference the value of another field, for example to check that two passwords match. In Valibot, you use a pipeline on the object schema with forward and partialCheck instead.
// Change this
const RegisterSchema = Joi.object({
password: Joi.string().required(),
confirmPassword: Joi.string()
.required()
.valid(Joi.ref('password'))
.messages({ 'any.only': 'The two passwords do not match.' }),
});
// To this
const RegisterSchema = v.pipe(
v.object({
password: v.pipe(v.string(), v.nonEmpty()),
confirmPassword: v.pipe(v.string(), v.nonEmpty()),
}),
v.forward(
v.partialCheck(
[['password'], ['confirmPassword']],
(input) => input.password === input.confirmPassword,
'The two passwords do not match.'
),
['confirmPassword']
)
);Conditional schemas
There is no direct equivalent to Joi's .when() method. For discriminated unions, we recommend variant. For other conditional validations, you can use check or rawCheck on the parent object, or select the schema dynamically with lazy, which receives the current input as an argument.
Error messages
Instead of .messages(), .message() and .label(), you pass a single string as the first argument to schemas and as the last argument to actions. See the quick start and internationalization guide for more details.
// Change this
const Schema = Joi.string().min(10).messages({
'string.base': 'Must be a string',
'string.min': 'String is too short',
});
// To this
const Schema = v.pipe(
v.string('Must be a string'),
v.minLength(10, 'String is too short')
);Async validation
Joi's .external() method allows asynchronous validation rules. Valibot provides dedicated async functions like parseAsync, pipeAsync and checkAsync for this purpose. See the async guide for more details.
// Change this
const Schema = Joi.string().external(async (value) => {
if (await isUsernameTaken(value)) {
throw new Error('Username is already taken');
}
return value;
});
// To this
const Schema = v.pipeAsync(
v.string(),
v.checkAsync(
async (input) => !(await isUsernameTaken(input)),
'Username is already taken'
)
);