Zod Tutorial (10 exercises)

Make Schemas Optional

Zod is also useful on the frontend.

In this example, we have a function called validateFormInput.

The values type is unknown, which is safe in this case because we only have a vague idea of the form's shape. In this case, we're collecting a name and phoneNumber as seen in the Form object schema:

In our code's current state, we have a failing test when a phone number is not included.


Because a phone number is not always required, find a way to update our Form so that it passes the validation test whether or not a phoneNumber string has been included.


Matt Pocock: Let's now jump to another really great use case for Zod, which is validating form inputs in a front-end application. We've got this function called validateFormInput, where we genuinely don't know what the values are. We vaguely know their shape, but it's pretty safe to just add unknown here.

We're collecting a name and a phone number here, except there's a tricky part here. This is the problem I want you to solve, which is that we want to be able to...The phone number should be optional here. They don't need to parse the phone number. We can just accept name. We're always going to need a name, but we're not always going to need a phone number.

That means that they can parse in undefined, or they can parse in nothing at all. Here should validate correct input. We're actually getting an error here, inside these tests, because this should be valid but it's not, essentially. You've got to find out a way from Zod's API to make this z.string optional.