Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Readme: Add example for string validation for an optional field to chapter "Unions" #1849

Merged
merged 2 commits into from
Jan 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,25 @@ For convenience, you can also use the [`.or` method](#or):
const stringOrNumber = z.string().or(z.number());
```

**Optional string validation:**

To validate an optional form input, you can union the desired string validation with an empty string [literal](#literals).

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( '' ),
] )

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

A discriminated union is a union of object schemas that all share a particular key.
Expand Down