Some questions
See original GitHub issueHello,
I’m giving a try of your lib in my project, and it looks quite nice.
I have some questions, sorry if this is not the best place to do it, but I didn’t find a tag in stackoverflow…
1 - Can I use this lib in the backend and frontend, or just in one of two?
2 - I’m trying to do the following rule: The bank property (an object) of an object (a React form) is required. But I don’t care about bank properties, just if it is informed (not undefined) or not, because it comes from an autocomplete component.
I’m doing like this:
z.object({
bank: z
.object({
id: z.union([z.number(), z.string()])
})
.nonstrict(),
Is this the best way?
3 - How to extend this lib with custom methods? For example, a string validation method to validate CPF (a SSN like number in my country). I did a refine and it worked well, but I’m thinking about extending the schema, like this:
z.string().cpf()
Can I just reexport zod with my custom methods like this:
const CustomZod = {
string: () =>
z.string().refine(
arg => validateCPF(arg),
{ message: "CPF inválido" }
)
};
Is this the best way?
4 - I’m using Formik, and in Formik the validation function receives an object of values and must return an object with the error messages, one message for each key. I’m doing like this:
const validateZod = (values: unknown): object => {
const parsingResult = props.validationSchema.safeParse(values);
if (parsingResult.success) {
return {};
}
const flattenedErrors = parsingResult.error.flatten();
const errors = {};
for (const [key, value] of Object.entries(flattenedErrors.fieldErrors)) {
errors[key] = value[0];
}
return errors;
};
Is this the best way?
5 - I want to add a functionality to add asterisks to required fields in Formik. So basically I would need to read the Zod schema passed to form, and check what fields of schema are required to put the asterisk. Basically a reverse engineering of sorts. How can I do that with Zod?
Thanks a lot.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
@julianomqs @tmtron just thought of a better
isOptional
implementation!So might be not be worth putting into core after all. 😛
Thanks a lot.