Valita

A typesafe validation & parsing library for TypeScript.

README

@badrap/valita


A TypeScript library for validating & parsing structured objects. The API is _heavily_ influenced by Zod's excellent API, while the implementation side aims for the impressive performance of simple-runtypes.

We also pay special attention for providing descriptive validation error messages:

  1. ```ts
  2. const vehicle = v.union(
  3.   v.object({ type: v.literal("plane"), airline: v.string() }),
  4.   v.object({ type: v.literal("train") }),
  5.   v.object({ type: v.literal("automobile"), make: v.string() })
  6. );
  7. vehicle.parse({ type: "bike" });
  8. // ValitaError: invalid_literal at .type (expected "plane", "train" or "automobile")
  9. ```

Installation


For Node.js


  1. ```sh
  2. npm i @badrap/valita
  3. ```

For Deno


  1. ```ts
  2. import * as v from "https://deno.land/x/valita/mod.ts";
  3. ```

Docs aren't my forté


A motivating example in lack of any better documentation:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const Pet = v.object({
  4.   type: v.union(v.literal("dog"), v.literal("cat")),
  5.   name: v.string(),
  6. });

  7. const Person = v.object({
  8.   name: v.string(),
  9.   age: v.number(),
  10.   pets: v.array(Pet).optional(),
  11. });
  12. ```

Now Person.parse(value) returns value if it matches the Person schema - or throws an error otherwise.

  1. ```ts
  2. const grizzlor = Person.parse({
  3.   name: "Grizzlor",
  4.   age: 101,
  5.   pets: [
  6.     { type: "cat", name: "Mittens" },
  7.     { type: "cat", name: "Parsley" },
  8.     { type: "cat", name: "Lulu" },
  9.     { type: "cat", name: "Thomas Percival Meowther III" },
  10.   ],
  11. });
  12. ```

The real magic here comes from TypeScript's type inference. The inferred type for grizzlor is:

  1. ```ts
  2. const grizzlor: {
  3.   name: string;
  4.   age: number;
  5.   pets?: { type: "dog" | "cat"; name: string }[] | undefined;
  6. };
  7. ```

You can use `Infer` to get your mitts on the inferred type in your code:

  1. ```ts
  2. type PersonType = v.Infer<typeof Person>;
  3. ```

API Reference


This section contains an overview of all validation methods.

Primitive Types


Let's start with the basics! Like every validation library we support all primitive types like strings, numbers, booleans, null, undefined and more.

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const developer = v.object({
  4.   name: v.string(),
  5.   age: v.number(),
  6.   usesValita: v.boolean(),
  7.   projects: v.array(v.string()),
  8.   null: v.null(),
  9.   undefined: v.undefined(),
  10.   bigNumber: v.bigint(),
  11. });
  12. ```

On top of that we support additional methods to coerce specific values to a certain TypeScript type:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const something = v.object({
  4.   shouldNotHappen: v.never(),
  5.   noClueWhatThisIs: v.unknown(),
  6. });
  7. ```

Nullable Type


When working with APIs/DBs some types are nullable. Valita can validate those types via the .nullable() method:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. // type name = null | string
  4. const name = v.string().nullable();

  5. // Passes
  6. name.parse("Jane Doe");
  7. // Passes
  8. name.parse(null);
  9. ```

Optional Object Properties


One common occurrence when working with APIs is that some fields in an object are optional and therefore can be missing completely. Valita can skip validating those via the .optional() method:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const person = v.object({
  4.   name: v.string(),
  5.   // Not everyone filled in their favorite song
  6.   song: v.string().optional(),
  7. });

  8. // Passes
  9. person.parse({ name: "Jane Doe", song: "Never gonna give you up" });
  10. // Passes
  11. person.parse({ name: "Jane Doe" });
  12. ```

Record Type


Whereas .object() can be used to validate objects, it has the limitation that all property keys have to be known upfront. It doesn't support an arbitrary number of properties, which is where Record types come to the rescue.

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. // Every property key must be known upfront
  4. const obj = v.object({
  5.   foo: v.number(),
  6.   bar: v.number(),
  7. });

  8. // ...with records
  9. const obj2 = v.record(v.number());
  10. ```

With the record type you're essentially specifying that there are (theoretically) an infinite number of property keys which are all of type string. The argument you pass to .record() is the type of the property values. In the example above all property values are numbers.

Tuple Types


Despite JavaScript not having tuple values (yet?), many APIs leverage plain arrays as an escape hatch. For example: If we encode a range between two numbers we'd likely choose type Range = [number, number] as the data type. From JavaScript's point of view it's just an array but TypeScript knows about the value of each position and that the array must have two entries.

We can express the same with valita:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const range = v.tuple([v.number(), v.number()]);

  4. // Passes
  5. range.parse([1, 2]);
  6. range.parse([200, 2]);

  7. // Fails
  8. range.parse([1]);
  9. range.parse([1, 2, 3]);
  10. range.parse([1, "2"]);
  11. ```

Union Types


A union type is a value which can have several different representations. Let's imagine we have a value of type Shape that can be either a circle, a square or a rectangle.

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const rectangle = v.object({ type: "rectangle" });
  4. const square = v.object({ type: "square" });
  5. const circle = v.object({ type: "circle" });

  6. // Validates either as "rectangle", "square" or "circle"
  7. const shape = v.union(rectangle, square, circle);
  8. ```

Note that although in this example all representations have a shared property type, it's not necessary at all. Each representation can be completely different:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const primitive = v.union(v.number(), v.string(), v.boolean());
  4. ```

Literal Types


Sometimes knowing if a value is of a certain type is not enough. We can use the .literal() method to check for actual values, like checking if a string is either "red", "green" or "blue" and not just any string.

  1. ```js
  2. import * as v from "@badrap/valita";

  3. const rgb = v.union(v.literal("red"), v.literal("green"), v.literal("blue"));
  4. ```

We can also use this to check for concrete numbers, bigint literals or boolean values too:

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const banana2YearsOld = v.object({
  4.   kind: v.literal("banana"),
  5.   age: v.literal(2),
  6.   isFresh: v.literal(true),
  7. });
  8. ```

For more complex values you can use the .assert()-method. Check out the Custom validation functions to learn more about it.

Custom validation functions


The .assert()-method can be used for custom validation logic like verifying that a number is inside a certain range for example.

  1. ```js
  2. import * as v from "@badrap/valita";

  3. const schema = v
  4.   .number()
  5.   .assert((v) => v >= 0 && v <= 255, "Must be in between 0 or 255");
  6. ```

Composing custom validation functions


A core strength of valita is that validation functions are composable by nature. This means that you can reuse bits and pieces of your schema and compose schemas from smaller building blocks.

  1. ```js
  2. import * as v from "@badrap/valita";

  3. // Reusable custom schema for a Person type
  4. const personSchema = v
  5.   .object({
  6.     name: v.string()
  7.     age: v.number(),
  8.   })

  9. // Reuse the custom schema times
  10. const schema = v.object({
  11.   person: personSchema,
  12.   otherPerson: personSchema,
  13. });
  14. ```

Custom validations with type casting


Whilst the .assert()-method is very powerful to check if a type is valid or not, it can only return a boolean value. But sometimes we want to parse our data into a propert type in one go. Imagine a JSON-API which serializes dates as a string type representing a unix timestamp and we want to return a valid Date in our validation schema.

  1. ```json
  2. {
  3.   "created_at": "2022-01-01T00:00:00.000+00:00"
  4. }
  5. ```

This can be done with the .chain()-method which allows you to cast to a certain type on top of validating the value. It's a more general alternative to .assert() so to say.

The .chain()-method receives a function to which it will pass the raw value as the first argument. If the value is deemed as being incorrect we return an error message via v.err("My message"). If not we cast it to the type we want and pass that to v.ok(value).

Similar to .assert() the .chain()-method must follow a preceding validation function like v.string() in our example.

  1. ```js
  2. import * as v from "@badrap/valita";

  3. const dateSchema = v.string().chain((str) => {
  4.   const date = new Date(str);

  5.   // If the date is invalid JS returns NaN here
  6.   if (isNaN(date.getTime())) {
  7.     return v.err(`Invalid date "${str}"`);
  8.   }

  9.   return v.ok(date);
  10. });

  11. const schema = v.object({
  12.   created_at: dateSchema,
  13. });
  14. ```

Recursive Types


One strong suit of valita is its ability to parse types that references itself, like type T = string | T[]. We can express such a shape with valita using the .lazy() method.

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. type T = string | T[];
  4. const myType: v.Type<T> = v.lazy(() => v.union(v.string(), v.array(myType)));
  5. ```

_Note that TypeScript needs an explicit type cast as it cannot interfere return types of recursive functions. That's why the variable is typed as `v.Type`._

Validating Self-Referencing Schemas


You may come across a schema where fields are related to each other and need to be validated together. Let's pick an example where a JSON-API returns an object with a min and max property. In our schema we want to ensure that the min value is smaller than max.

  1. ```json
  2. {
  3.   "min": 10,
  4.   "max": 100
  5. }
  6. ```

For that we assert that both properties are of type number via the .number()-method. To be able to compare them to each other we add a validation helper on the common parent type of the fields we want to compare. We can leverage the .assert()-method on the surrounding .object() result in our example.

  1. ```ts
  2. import * as v from "@badrap/valita";

  3. const schema = v
  4.   .object({
  5.     min: v.number(),
  6.     max: v.number(),
  7.   })
  8.   .assert((obj) => obj.min < obj.max, ".min must be smaller than .max");
  9. ```

License


This library is licensed under the MIT license. See LICENSE.