I'm currently developing a robust Zod validation schema for an input field that handles product names. This schema needs to be able to adapt to various validation requirements, such as minimum/maximum length and the inclusion of special characters.
Below is a simplified version of the schema:
const { minLength = 3, maxLength = 50, allowSpecialCharacters = false, required = true } = options || {};
let schema = z.string({ required_error: `${displayName} is required` });
if (required) {
schema = schema.min(minLength, { message: `${displayName} must be at least ${minLength} characters long` });
}
schema = schema.max(maxLength, { message: `${displayName} must be less than ${maxLength} characters` });
if (!allowSpecialCharacters) {
schema = schema.refine((value) => /^[a-zA-Z0-9\s]*$/.test(value), {
message: `${displayName} must not contain special characters`
});
}
return schema.trim();
}
However, I've run into a TypeScript error when trying to reassign 'schema' within the conditional statements:
Type 'ZodEffects<ZodString, string, string>' is missing the following properties from type 'ZodString': _regex, _addCheck, email, url, and 39 more.ts(2740)
let schema: z.ZodString
It appears that after applying 'refine', Zod returns a 'ZodEffects' type instead of 'ZodString', causing a type mismatch. How can I conditionally chain these refinements while maintaining proper type compatibility? Any suggestions or insights would be greatly appreciated!