How to add asterisk on an input's label from a schema validation with hookform/resolver #10413
Unanswered
yann-lauwers
asked this question in
Q&A
Replies: 1 comment
-
What i do is i put the Schema in a context, then use zod-to-json-schema library, it generate Zod Schema to readable object: import React from "react";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
type ZodSchemaContextValue = {
schema: z.ZodType;
};
interface ZodSchemaProviderProps {
schema: z.ZodType;
children: React.ReactNode;
}
const SchemaContext = React.createContext<ZodSchemaContextValue | null>(null);
const ZodSchemaProvider = ({ schema, children }: ZodSchemaProviderProps) => {
return (
<SchemaContext.Provider value={{ schema }}>
{children}
</SchemaContext.Provider>
);
};
const useZodSchema = () => {
const context = React.useContext(SchemaContext);
if (!context) {
throw new Error("useSchema must be used within a ZodSchemaProvider");
}
const jsonSchemaFull = zodToJsonSchema(context.schema) as {
properties: any;
required: string[];
};
const getJsonSchema = (
inputPath: string
): {
isRequired: boolean;
[key: string]: any;
} => {
const parts = inputPath.split(".");
let currentSchema = jsonSchemaFull.properties;
let requiredFields = jsonSchemaFull.required;
for (let i = 0; i < parts.length; i++) {
if (currentSchema && currentSchema[parts[i]]) {
currentSchema = currentSchema[parts[i]];
if (currentSchema.items?.properties) {
requiredFields = currentSchema.items.required;
currentSchema = currentSchema.items.properties[parts[i + 2]];
}
}
}
return {
isRequired: requiredFields.includes(parts[parts.length - 1]),
description: currentSchema.description,
...currentSchema,
};
};
return {
schema: context.schema,
jsonSchema: jsonSchemaFull,
getJsonSchema: getJsonSchema,
};
};
export { useZodSchema, ZodSchemaProvider }; Then i just call it like this: const { getJsonSchema } = useZodSchema();
const { isRequired } = getJsonSchema(name); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
How can I add an asterisk to my input's label based on the validation schema?
I'm using Zod to validate my forms within my app. I would like to add an asterisk on each label's input which is required without passing a props from the parent. It would duplicate the job + it looks like a bad implementation because I would have :
My input know but my label not..
I would like to do something like
I recreated a small version of the situation in this sandbox.
I want the
lastName
's label to have an * since it is required in the schema.Is the any function I can use from RHF to achieve that ?
Would be very appreciated 🚀
Beta Was this translation helpful? Give feedback.
All reactions