Zod Section 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:

const Form = z.object({
  name: z.string
Loading solution

Transcript

Matt Pocock: 0:00 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.

0:17 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.

0:28 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.

0:38 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.

0:50 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.