# Validate recipes

> Check recipe input from a CMS, an API, or a form at runtime, and report every issue with its path.

Source: https://recipe-book.siraj.page/guides/validate-recipes/

Validate recipe input that TypeScript can't check because it arrives at runtime, from a content management system (CMS), a database, an API response or request body, or a form. Pass it to [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), which accepts `unknown`, checks every field, and returns a [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe) or every issue it found. In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports. Except for an error thrown by a getter or a proxy in the input, which passes through, `parseRecipe` doesn't throw for bad input, so branch on `success`:

```ts
import { parseRecipe } from '@recipe-book/core'

export async function getRecipe(url: string) {
  const response = await fetch(url)
  const result = parseRecipe(await response.json())

  if (!result.success) {
    throw result.error
  }

  return result.data
}
```

`result.error` is an `Error` whose message lists the first 10 issues, so throwing it gives a readable failure. Warnings count toward the 10, so when 10 warnings come first, the issues that failed the parse are only in `error.issues`. Where you catch it, pass it to [`isRecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#isrecipevalidationerror) before reading its [issues](https://recipe-book.siraj.page/guides/validate-recipes.md#read-issues): TypeScript then types `error.issues` with no cast. To keep recipes in a database, store `result.data` and validate it again when you load it, as [Store the recipe](https://recipe-book.siraj.page/guides/import-recipes.md#store-the-recipe) shows.

## Read issues

`parseRecipe` doesn't stop at the first problem, so you see every issue at once:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  yield: '4',
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cupz' },
    { name: 'egg', quantity: 2, optional: 'no' },
  ],
  steps: ['Whisk the dry ingredients in a large bowl.'],
})

if (!result.success) {
  console.log(result.error.message)
}
```

result.error.message
```txt title="result.error.message"
"Buttermilk pancakes" has 3 problems:
  ✖ yield                    Add what the recipe makes, e.g. "24 cookies". For a number of servings, use servings: 4.
  ✖ ingredients[0].quantity  Unknown unit "cupz". Did you mean "cups"?
  ✖ ingredients[1].optional  Expected true or false, received "no".
See https://recipe-book.siraj.page/errors/invalid_recipe/
```

`result.error.issues` has each [issue](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue) as data, with a `code`, a `severity`, a `message`, and a `path` to the value, a list of keys and indexes such as `['ingredients', 0, 'quantity']`. Some issues also have a `suggestion`, so you can offer a "Did you mean" hint: a likely misspelled unit gets the unit it misspells, such as `'cups'` for `"cupz"`; a field name close to a known one gets that one, such as `'steps'` for `stepz`; another format's name for a field gets that field, such as `'name'` for a top-level `title`; the system `'imperial'` gets `'us'`; the yield `'4 and 6 loaves'` gets `'4-6 loaves'`; and with `{ parseIngredientLine }`, the ingredient line `'2 and 1/2 cups flour'` gets an `invalid_quantity` warning suggesting `'2 1/2 cups'`. [Issue codes](https://recipe-book.siraj.page/errors.md#issue-codes) lists every code with its severity, what it means, and how to fix it.

To see the issues `parseRecipe(input, { parseIngredientLine })` gives your own recipe input, paste it into the [playground](https://recipe-book.siraj.page/playground/) as JSON rather than as a JavaScript object like the ones on this page. Without [`{ parseIngredientLine }`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), a text ingredient such as `'2 cups flour'` is an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) error instead.

## Validate a form

Form fields give their values as strings. To show each issue next to its form field, match the field to `issue.path.join('.')`:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: '4',
  ingredients: [
    { name: 'all-purpose flour', quantity: '' },
    { name: 'egg', quantity: '2', optional: 'on' },
  ],
  steps: ['Whisk the dry ingredients in a large bowl.'],
})

if (!result.success) {
  result.error.issues.map((issue) => [issue.path.join('.'), issue.message]) // [['ingredients.0.quantity', 'Expected a quantity such as "1 ½ cups", received an empty string.'], ['ingredients.1.optional', 'Expected true or false, received "on".']]
}
```

Servings, yields, and quantities can be strings, as `'4'` shows, but a time in minutes must be a number, so pass a time field through `Number()`. Leave out a servings, yield, quantity, or time field the reader left empty, and for `optional`, pass a checkbox's `checked` rather than the `'on'` it submits.

## Handle warnings

Issues with the severity `warning` don't fail the parse. When it succeeds, `result.warnings` lists them; when it fails, `result.error.issues` lists them with the issues that failed it. An [`unknown_field`](https://recipe-book.siraj.page/errors.md#issue-unknown_field) warning means the parse dropped that field, as these misspelled fields show:

```ts {5-7}
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  serving: 4,
  ingredients: [{ name: 'egg', quantiy: 2 }],
  step: ['Whisk the eggs.'],
})

if (!result.success) {
  throw result.error
}

result.warnings.map((issue) => issue.message) // ['Unknown field. Did you mean "quantity"?', 'Recipe has no steps.', 'Unknown field. Did you mean "servings"?', 'Unknown field. Did you mean "steps"?']
```

The recipe parses, but without its servings, its steps, or the egg's quantity. To fail a content build on any issue, treat warnings as errors: check `result.warnings.length` too.

## Validate with Standard Schema

[`recipeSchema`](https://recipe-book.siraj.page/reference/core/parsing.md#recipeschema) wraps `parseRecipe` in the [Standard Schema](https://standardschema.dev) format, so libraries that accept a Standard Schema can validate recipe input with it. It reads ingredient objects only; for ingredient lines, make a schema with [`createRecipeSchema({ parseIngredientLine })`](https://recipe-book.siraj.page/reference/core/parsing.md#createrecipeschema). In tRPC 11, pass it to `.input()`, and `input` is a `Recipe`:

```ts {8}
import { recipeSchema } from '@recipe-book/core'
import { initTRPC } from '@trpc/server'

const t = initTRPC.create()

export const appRouter = t.router({
  saveRecipe: t.procedure
    .input(recipeSchema)
    .mutation(({ input }) => input.id),
})
```

The library gets only the issues with the severity `error`, each with a `message` and a `path`.

`recipeSchema` isn't a Zod or Valibot schema, so it can't be a field inside `z.object()` or `v.object()`. There's no JSON Schema for recipe input either: check it with `parseRecipe` or `recipeSchema`.

## Next steps

- [Parsing](https://recipe-book.siraj.page/reference/core/parsing.md) for `parseRecipe`, `recipeSchema`, and [`ParseResult`](https://recipe-book.siraj.page/reference/core/parsing.md#parseresult)
- [Issue codes](https://recipe-book.siraj.page/errors.md#issue-codes) for every issue code and its fix
- [Errors](https://recipe-book.siraj.page/reference/core/errors.md) for [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) and [`RecipeIssue`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue)
- [Author recipes](https://recipe-book.siraj.page/guides/author-recipes.md) for the forms recipe input takes
- [Import recipes](https://recipe-book.siraj.page/guides/import-recipes.md) for recipes from other sites' pages
