Skip to content

Commit

Permalink
docs: punctuation (#1973)
Browse files Browse the repository at this point in the history
* docs: punctuation

* Tweaks

---------

Co-authored-by: Colin McDonnell <colinmcd@alum.mit.edu>
  • Loading branch information
jly36963 and Colin McDonnell committed Feb 8, 2023
1 parent 1a033b2 commit 1e74925
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 116 deletions.
120 changes: 62 additions & 58 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,19 +745,19 @@ z.date().max(new Date(), { message: "Too young!" });
Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`.
```ts
const dateSchema = z.coerce.date()
type DateSchema = z.infer<typeof dateSchema>
const dateSchema = z.coerce.date();
type DateSchema = z.infer<typeof dateSchema>;
// type DateSchema = Date

/* valid dates */
console.log( dateSchema.safeParse( '2023-01-10T00:00:00.000Z' ).success ) // true
console.log( dateSchema.safeParse( '2023-01-10' ).success ) // true
console.log( dateSchema.safeParse( '1/10/23' ).success ) // true
console.log( dateSchema.safeParse( new Date( '1/10/23' ) ).success ) // true
console.log(dateSchema.safeParse("2023-01-10T00:00:00.000Z").success); // true
console.log(dateSchema.safeParse("2023-01-10").success); // true
console.log(dateSchema.safeParse("1/10/23").success); // true
console.log(dateSchema.safeParse(new Date("1/10/23")).success); // true

/* invalid dates */
console.log( dateSchema.safeParse( '2023-13-10' ).success ) // false
console.log( dateSchema.safeParse( '0000-00-00' ).success ) // false
console.log(dateSchema.safeParse("2023-13-10").success); // false
console.log(dateSchema.safeParse("0000-00-00").success); // false
```
For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276).
Expand Down Expand Up @@ -1301,16 +1301,13 @@ To validate an optional form input, you can union the desired string validation
This example validates an input that is optional but needs to contain a [valid URL](#strings):
```ts
const optionalUrl = z.union( [
z.string().url().nullish(),
z.literal( '' ),
] )
const optionalUrl = z.union([z.string().url().nullish(), z.literal("")]);

console.log( optionalUrl.safeParse( undefined ).success ) // true
console.log( optionalUrl.safeParse( null ).success ) // true
console.log( optionalUrl.safeParse( '' ).success ) // true
console.log( optionalUrl.safeParse( 'https://zod.dev' ).success ) // true
console.log( optionalUrl.safeParse( 'not a valid url' ).success ) // false
console.log(optionalUrl.safeParse(undefined).success); // true
console.log(optionalUrl.safeParse(null).success); // true
console.log(optionalUrl.safeParse("").success); // true
console.log(optionalUrl.safeParse("https://zod.dev").success); // true
console.log(optionalUrl.safeParse("not a valid url").success); // false
```
## Discriminated unions
Expand All @@ -1325,7 +1322,7 @@ type MyUnion =
Such unions can be represented with the `z.discriminatedUnion` method. This enables faster evaluation, because Zod can check the _discriminator key_ (`status` in the example above) to determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod report friendlier errors.
With the basic union method the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option".
With the basic union method, the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option".
```ts
const myUnion = z.discriminatedUnion("status", [
Expand Down Expand Up @@ -1474,59 +1471,64 @@ type Teacher = z.infer<typeof Teacher>;
You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".

```ts
const baseCategorySchema = z.object( {
name: z.string(),
} )
const baseCategorySchema = z.object({
name: z.string(),
});

type Category = z.infer<typeof baseCategorySchema> & {
subcategories: Category[]
}
subcategories: Category[];
};

const categorySchema: z.ZodType<Category> = baseCategorySchema.extend( {
subcategories: z.lazy( () => categorySchema.array() ),
} )
const categorySchema: z.ZodType<Category> = baseCategorySchema.extend({
subcategories: z.lazy(() => categorySchema.array()),
});

categorySchema.parse( {
name: 'People',
subcategories: [ {
name: 'Politicians',
subcategories: [ {
name: 'Presidents',
subcategories: []
} ],
} ],
} ) // passes
categorySchema.parse({
name: "People",
subcategories: [
{
name: "Politicians",
subcategories: [
{
name: "Presidents",
subcategories: [],
},
],
},
],
}); // passes
```

Thanks to [crasite](https://github.com/crasite) for this example.

### ZodType with ZodEffects

When using `z.ZodType` with `z.ZodEffects` (
[`.refine`](https://github.com/colinhacks/zod#refine),
[`.transform`](https://github.com/colinhacks/zod#transform),
[`preprocess`](https://github.com/colinhacks/zod#preprocess),
etc...
[`.refine`](https://github.com/colinhacks/zod#refine),
[`.transform`](https://github.com/colinhacks/zod#transform),
[`preprocess`](https://github.com/colinhacks/zod#preprocess),
etc...
), you will need to define the input and output types of the schema. `z.ZodType<Output, z.ZodTypeDef, Input>`

```ts
const isValidId = ( id: string ): id is `${ string }/${ string }` =>
id.split( '/' ).length === 2
const isValidId = (id: string): id is `${string}/${string}` =>
id.split("/").length === 2;

const baseSchema = z.object( {
id: z.string().refine( isValidId )
} )
const baseSchema = z.object({
id: z.string().refine(isValidId),
});

type Input = z.input<typeof baseSchema> & {
children: Input[]
}
children: Input[];
};

type Output = z.output<typeof baseSchema> & {
children: Output[]
}
children: Output[];
};

const schema: z.ZodType<Output, z.ZodTypeDef, Input> = baseSchema.extend( {
children: z.lazy( () => schema.array() ),
} )
const schema: z.ZodType<Output, z.ZodTypeDef, Input> = baseSchema.extend({
children: z.lazy(() => schema.array()),
});
```

Thanks to [marcus13371337](https://github.com/marcus13371337) and [JoelBeeldi](https://github.com/JoelBeeldi) for this example.
Expand Down Expand Up @@ -1735,7 +1737,7 @@ stringSchema.parse(12); // throws error

`.parseAsync(data:unknown): Promise<T>`

If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`
If you use asynchronous [refinements](#refine) or [transforms](#transform) (more on those later), you'll need to use `.parseAsync`.

```ts
const stringSchema = z.string().refine(async (val) => val.length <= 8);
Expand All @@ -1758,7 +1760,7 @@ stringSchema.safeParse("billie");
// => { success: true; data: 'billie' }
```

The result is a _discriminated union_ so you can handle errors very conveniently:
The result is a _discriminated union_, so you can handle errors very conveniently:

```ts
const result = stringSchema.safeParse("billie");
Expand Down Expand Up @@ -2018,7 +2020,7 @@ emailToDomain.parse("colinhacks@example.com"); // => example.com

The `.transform` method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining `transform` and `refine`.

As with `.superRefine`, the transform function receives a `ctx` object with a `addIssue` method that can be used to register validation issues.
As with `.superRefine`, the transform function receives a `ctx` object with an `addIssue` method that can be used to register validation issues.

```ts
const numberInString = z.string().transform((val, ctx) => {
Expand Down Expand Up @@ -2097,8 +2099,10 @@ Conceptually, this is how Zod processes default values:
Use `.describe()` to add a `description` property to the resulting schema.

```ts
const documentedString = z.string().describe("A useful bit of text, if you know what to do with it.");
documentedString.description // A useful bit of text…
const documentedString = z
.string()
.describe("A useful bit of text, if you know what to do with it.");
documentedString.description; // A useful bit of text…
```

This can be useful for documenting a field, for example in a JSON Schema using a library like [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema)).
Expand Down Expand Up @@ -2367,7 +2371,7 @@ if (!data.success) {

> For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: [ERROR_HANDLING.md](ERROR_HANDLING.md)
Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error)
Zod's error reporting emphasizes _completeness_ and _correctness_. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third-party library like [`zod-validation-error`](https://github.com/causaly/zod-validation-error)

### Error formatting

Expand Down
Loading

0 comments on commit 1e74925

Please sign in to comment.