Zod - TypeScript-first schema declaration and validation library #6

Nhan Nguyen - Dec 10 '23 - - Dev Community

Image description

Make Schemas Optional

We have a function called validateFormInput:

Image description

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 are collecting a name and phoneNumber as seen in the Form object schema:

Image description

We have a failing test when a phone number is not included.

We need to update our Form to pass the validation test whether or not a phoneNumber string has been included.

By adding .optional() onto the end of our phoneNumber schema, our test will pass:

Image description

What we are saying here is that name is a string, and phoneNumber is either a string or undefined.

We do not have to parse anything, making this an excellent way to set a property as optional.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player