Skip to content

Commit

Permalink
Merge pull request #1849 from tordans/patch-5
Browse files Browse the repository at this point in the history
Readme: Add example for string validation for an optional field to chapter "Unions"
  • Loading branch information
JacobWeisenburger committed Jan 10, 2023
2 parents 537fb44 + 935c4b9 commit 744fc38
Showing 1 changed file with 19 additions and 0 deletions.
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

0 comments on commit 744fc38

Please sign in to comment.