JavaScript

Schema libraries

The validators of Brazilian Utils inside a Zod, Valibot or ArkType schema, or as a Standard Schema of their own.

A guide from the JavaScript library. Source file

Functions used: CEP: Validate, CNPJ: Validate, CPF: Validate, Phone: Validate

A validator goes straight into a schema: pick the document and the schema library. Nothing runs here, a schema is the same code everywhere.

Each of these builds the document on its own first, so it can be reused wherever a schema needs it, and composes it into a form afterwards. They all speak Standard Schema, which is how a schema reaches a form library, and toStandardSchema gives one validator that same interface with no schema library at all.

refine takes the validator as it is:

cpf-zod.ts
import { isValidCpf } from "@brazilian-utils/brazilian-utils";
import { z } from "zod";

/** A CPF, reusable wherever a schema needs one. */
export const cpfSchema = z.string().refine(isValidCpf, "Enter a valid CPF");

export const signupSchema = z.object({
  name: z.string().min(1, "Enter your name"),
  cpf: cpfSchema,
});

export type Signup = z.infer<typeof signupSchema>;
cnpj-zod.ts

Loading the code…

cep-zod.ts

Loading the code…

phone-zod.ts

Loading the code…

check takes the validator inside a pipe:

cpf-valibot.ts

Loading the code…

cnpj-valibot.ts

Loading the code…

cep-valibot.ts

Loading the code…

phone-valibot.ts

Loading the code…

narrow takes it, and says what the value must be when it says no:

cpf-arktype.ts

Loading the code…

cnpj-arktype.ts

Loading the code…

cep-arktype.ts

Loading the code…

phone-arktype.ts

Loading the code…

No schema library at all: toStandardSchema gives the validator the interface every form library speaks. VeeValidate takes it as rules from version 5 on, and Hono validates an object, so its route wraps the validator for the JSON body.

cpf-standard.ts

Loading the code…

cnpj-standard.ts

Loading the code…

cep-standard.ts

Loading the code…

phone-standard.ts

Loading the code…

The utilities reference documents toStandardSchema and the types of the specification.