The Snippets
The emptyStringToUndefined
uses z.literal("")
schema to represent a literal empty string. The transform
method is the used to convert the empty string to undefined
.
The function asOptionalField
takes a zod schema as its parameter. It then makes use of the zod optional
method to make the field optional, and it combines this with the or
method to include the emptyStringToUndefined
transform. This means that the resulting schema will accept either the original value, or an empty string (which will be transformed to undefined
).
In summary, the asOptionalField
function is designed to take any Zod schema and make it optional, allowing it to accept either the original value or an empty string (transformed to undefined
). This can be useful when dealing with optional fields in data validation scenarios.
How to Use
In this context, we utilize the asOptionalField
to validate the input of a WhatsApp number. The methods min()
, max()
, startsWith()
, and regex()
will only be invoked if the WhatsApp number input is neither undefined
nor an empty string ("").
Categories : typescriptzoddata validation