Zod Tutorial (10 exercises)
solution

Complex Schema Validation

The strings section of the Zod docs includes several examples of validation helpers that can be used to make our tests pass.

Here's what the Form schema looks like now:

Name has min(1) added because we can't pass in an empty string.

Phone numbers are constrained with min(5) and max(20) while still being optional.

Zod also has built-in validators for email and urls, saving us from writing our own.

Note that we can't use .optional().min() because min doesn't exist on the optional types. This means we have to put .optional() at the end after other validations.

There are additional validation resources linked in the Zod docs.

Transcript

Matt Pocock: Our form schema looks quite a bit different now. We've go this name, which is z.string().min. We actually don't have a test for this, but what it means is you can't parse a string which is less than one character. You can't parses an empty string. Really useful.

We've also got this phoneNumber here where we say z.string(). The minimum length is 5 and the maximum length is 20, which is doing pretty well with our test down here. It's also still optional there, too.

We've got email, which is z.string().email(), so you now can't pass an invalid email there. We've also got website, which is z.string().url. Again, it's optional here.

One thing to note with optional is that you can't put it here because .min doesn't exist on the types there, which is a little bit janky, but it means that optional goes at the end after the validations. I think that's fine.

Now, that means all our tests are passing. As you can see, there are a bunch of these. I don't want to cover them all in depth because it would take a while. If you are having a common validation issue with Zod, then there's probably a helper function to help you out.