Make Schemas Optional
Zod is also useful on the frontend.
In this example, we have a function called
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
phoneNumber as seen in the
Form object schema:
Matt Pocock: 0:00 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.
0:14 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.
0:35 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.