I want to build a custom Zod validator as follows:
const stringOrNumberValidator = (val: any) => {
if (typeof val === "number" && !isNaN(val)) {
return val;
} else if (typeof val === "string" && !isNaN(Number(val))) {
return Number(val);
} else {
return "Invalid";
}
};
const stringOrNumber = z.custom(stringOrNumberValidator);
const xSchema = z.object({
age: stringOrNumber,
});
const data = {
age: "2s0"
};
const ret = xSchema.safeParse(data);
console.log(ret);
The above does not work and always returns success as true. If I throw an error instead of return "Invalid"
, the error gets thrown and execution stops although I have used safeParse
I further want to extend the validation using the inbuilt Zod functions like min, max as follows
const xSchema = z.object({
age: stringOrNumber.min(5).max(25)
});
How can I achieve this?
Would you want to use it inside a form? with react-hook-form for example?
1